I want to create a simple CRUD application to test out the data handling capabilities of the Blackberry.
How do I create a simple save functio开发者_运维百科n?
In this example I'm storing a vector in the persistent store.
You have to come up with a store ID, which should be of type long. I usually create this by concating the fully qualified Application's Class name to some string that makes it unique with in my application.
//class Fields...
//Use the application fully qualified name so that you don't have store collisions.
static String ApplicaitonID = Application.getApplication().getClass().getName();
static String STORE_NAME = "myTestStore_V1";
long storeId = StringUtilities.stringHashToLong( ApplicationID + STORE_NAME );
private static PersistentObject myStoredObject;
private static ContentProtectedVector myObjects;
//End class fields.
Example of loading a Vector from the store:
myStoredObject = PersistentStore.getPersistentObject( storeId );
myObjects = (ContentProtectedVector) myStoredObject.getContents();
//Print the number of objects in storeage:
System.out.println( myObjects.size() );
//Insert an element and update the store on "disk"...
myObjects.addElement( "New String" );
myStoredObject.setContents(myObjects);
myStoredObject.commit();
Example of initializing this store and saving it to disk for the first time:
myStoredObject = PersistentStore.getPersistentObject( storeId );
myObjects = (ContentProtectedVector) myStoredObject.getContents();
if(myObjects == null)
myObjects = new ContentProtectedVector();
myStoredObject.setContents(myObjects);
myStoredObject.commit();
If you want to commit changes (aka save changes to disk), you need to repeat the bottom two lines. setContents(OBJ); and Commit().
You can store the following without having to do anything special:
java.lang.Boolean java.lang.Byte java.lang.Character java.lang.Integer java.lang.Long java.lang.Object java.lang.Short java.lang.String java.util.Vector java.util.Hashtable
@see : http://docs.blackberry.com/en/developers/deliverables/17952/Storing_objects_persistently_1219782_11.jsp
To store your own Classes, they (and all sub classes) have to implement the "Persistable" interface. I recommend that you do this, as these stores get cleaned up automatically when your application is uninstalled. This is because the OS cleans stored objects up, when "any" referenced classname in the store no longer has an application associated with it. So if your store is only using Strings, it's never going to get cleaned up.
精彩评论