我正在尝试将用户的注册状态存储在我的应用中。我使用过Persistent商店。但我没有从商店获取数据bak。我写了下面的代码:
package com.saiservices.util;
import java.util.Enumeration;
import com.saiservices.ui.Logger;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.util.Persistable;
public class SaiPersistentStore implements Persistable{
private SaiHashTable mElements = null;
static SaiPersistentStore instance;
private static final long KEY = xxxxxxxxxxxx;
private PersistentObject persistentObject = null;
/**
* Gets the single instance of DataBase.
*
* @return single instance of DataBase
*/
public static SaiPersistentStore getInstance() {
try {
if (instance == null) {
instance = new SaiPersistentStore();
}
} catch (Exception e) {
instance = null;
}
return instance;
}
private SaiPersistentStore()
{
Logger.out("PersistentStoreInfo", "inside constructor ");
persistentObject = PersistentStore.getPersistentObject(KEY);
synchronized (persistentObject)
{
if (persistentObject.getContents() == null)
{
persistentObject.setContents(new SaiHashTable());
persistentObject.commit();
}
}
mElements = (SaiHashTable)persistentObject.getContents();
if (mElements == null){
Logger.out("PersistentStoreInfo", "************"+(mElements == null));
mElements = new SaiHashTable();
}
}
public String getElement(String key)
{
Logger.out("PersistentStoreInfo", "getElement :"+key);
Logger.out("PersistentStoreInfo", "getElement value :"+mElements.get(key));
return (String) mElements.get(key);
}
public void setElement(String key, String value)
{
Logger.out("PersistentStoreInfo", "setElement11111 :"+key + " "+value);
mElements.put(key, value);
persistentObject.setContents(mElements);
Logger.out("PersistentStoreInfo", "setElement22222 :"+key+" "+value);
persistentObject.commit();
}
public Enumeration getAllKeys()
{
return mElements.keys();
}
}
这是哈希表代码:
package com.saiservices.util;
import java.util.Hashtable;
import net.rim.device.api.util.Persistable;
public class SaiHashTable extends Hashtable implements Persistable{
public SaiHashTable(){
super();
}
public SaiHashTable(int initialCepacity){
super(initialCepacity);
}
}
现在我正在设置这样的元素:
SaiPersistentStore.getInstance().setElement("Registration","on");
但是当我试图以这种方式获取元素时,获取空值:
SaiPersistentStore.getInstance().getElement("Register")
我在哪里做错了?请帮忙。
答案 0 :(得分:3)
从setElement()
方法中删除以下行:
persistentObject.setContents(mElements);
通过执行此操作,您将覆盖persaint对象的内容,这些对象早先是SaiHashTable对象。因此,下次当您尝试强制转换持久对象的内容时,会得到一个异常,您将捕获该异常,然后重置该实例。
此外,您应该尝试获得您设置的相同值:
SaiPersistentStore.getInstance().getElement("Registration")