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