我面临着在持久性存储中存储数据的问题,我试图在持久性存储中存储不同日期的事件但是数据被覆盖的代码是:
public ListEventScreen(Vector v,String timezone) {
for(int i=0;i<v.size();i++){
EventBean bean=(EventBean)v.elementAt(i);
//a normal label in the app, just to display text, anchored left
LabelField label = new LabelField(bean.getSummary(),LabelField.FIELD_LEFT);
//add the label to the screen
add(label);
saveUserInfo(v);
}
}
public void saveUserInfo(Vector vectorData){
// static{
store = PersistentStore.getPersistentObject( 0x1dfc10ec9447eb14L );
synchronized(store) {
store.setContents(vectorData);
store.commit();
}
//}
}
请告诉我必须更改的内容。
答案 0 :(得分:1)
每次拨打store.setContents()
时,persistentStore
的当前内容都会被您传入的Vector
覆盖。您需要确保加载以前的活动已经在persistentStore
中的Vector
之前,然后将新事件添加到您正在保存的Vector
中。
您还在saveUserInfo()
的循环的每次迭代中调用ListEventScreen()
。你应该在循环之外调用它。
我会做这样的事情:
public ListEventScreen(Vector v,String timezone) {
Enumeration e = v.elements();;
while (e.hasMoreElements()){
EventBean bean = (EventBean) e.nextElement();
//a normal label in the app, just to display text, anchored left
LabelField label = new LabelField(bean.getSummary(),LabelField.FIELD_LEFT);
//add the label to the screen
add(label);
}
}
public void loadUserInfo(Vector vectorData){
// static{
store = PersistentStore.getPersistentObject( 0x1dfc10ec9447eb14L );
synchronized(store) {
Vector v = (Vector) store.getContents();
Enumeration e = v.elements();
while (e.hasMoreElemens){
vectorData.add(e.nextElement());
}
}
//}
}
public void saveUserInfo(Vector vectorData){
// static{
store = PersistentStore.getPersistentObject( 0x1dfc10ec9447eb14L );
synchronized(store) {
store.setContents(vectorData);
store.commit();
}
//}
}
{
Vector v = new Vector();
loadUserInfo(v);
ListEventScreen(v, ...);
... modify v contents as needed ...
saveUserInfo(v);
}
如果您不介意更改持久性商店内容的格式,我会将商店换成单例类:
public class EventBeans extends Vector implements Persistable
{
private static final long persistKey = 0x1dfc10ec9447eb14L;
private static EventBeans _instance = null;
private static PersistentObject _persist = null;
static{
_persist = PersistentStore.getPersistentObject(persistKey);
_instance = (EventBeans) _persist.getContents();
if (_instance == null){
_instance = new EventBeans();
_persist.setContents(_instance);
_persist.commit();
}
}
private EventBeans(){
super();
}
public static EventBeans getInstance(){
return _instance;
}
public static synchronized void save(){
_persist.commit();
}
}
{
Vector v = EventBeans.getInstance();
ListEventScreen(v, ...);
... modify v contents as needed ...
EventBeans.save();
}