1

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

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

4

1 回答 1

5

在此示例中,我将向量存储在持久存储中。

你必须想出一个商店 ID,它应该是 long 类型。我通常通过将完全限定的应用程序的类名称连接到一些字符串来创建它,使其在我的应用程序中是唯一的。

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

如果要提交更改(也就是将更改保存到磁盘),则需要重复底部两行。设置内容(OBJ);和提交()。

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

java.lang.Boolean
java.lang.字节
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”接口。我建议您这样做,因为当您的应用程序被卸载时,这些存储会自动清理。这是因为当存储中“任何”引用的类名不再有与之关联的应用程序时,操作系统会清理存储的对象。因此,如果您的商店只使用字符串,它永远不会被清理干净。

于 2010-09-27T23:42:07.600 回答