如何在Blackberry中使用持久对象存储?

时间:2010-09-27 15:13:36

标签: blackberry persistent-object-store

我想创建一个简单的CRUD应用程序来测试Blackberry的数据处理功能。

如何创建简单的保存功能?

1 个答案:

答案 0 :(得分:5)

在这个例子中,我将向量存储在持久性存储中。

您必须提供商店ID,其类型应为long。我通常通过将完全限定的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.

从商店加载Vector的示例:

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();

首次初始化此商店并将其保存到磁盘的示例:

myStoredObject = PersistentStore.getPersistentObject( storeId ); 
myObjects = (ContentProtectedVector) myStoredObject.getContents();
if(myObjects == null)
    myObjects = new ContentProtectedVector(); 
myStoredObject.setContents(myObjects);
myStoredObject.commit();

如果要提交更改(即将更改保存到磁盘),则需要重复底部的两行。 setContents(OBJ);和Commit()。

您可以存储以下内容而无需执行任何特殊操作:

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

要存储您自己的类,它们(以及所有子类)必须实现“Persistable”接口。我建议您这样做,因为这些商店会在您卸载应用程序时自动清理。这是因为当存储中的“任何”引用的类名不再具有与之关联的应用程序时,操作系统会清除存储的对象。因此,如果您的商店只使用字符串,它将永远不会被清理。

相关问题