views:

47

answers:

1

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 function?

+2  A: 
//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:

myStoredObject = PersistentStore.getPersistentObject( storeId ); 
myObjects = (ContentProtectedVector) myStoredObject.getContents();
if(myObjects == null)
    myObjects = new ContentProtectedVector(); 
myStoredObject.setContents(myObjects);
myStoredObject.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.

eSniff