我有一個HashMap,其中包含與特定活動相關的數據。問題是,當應用程序閒置一段時間後打開時,HashMap是空的。我正在獲取主要活動中的所有數據,並將相應的對象存儲在自定義類中的HashMap中。除了有些時候應用程序閒置了很長時間之後,一切都運行良好,然後HashMap爲所有鍵返回空值。只要有我的應用程序正在運行的實例,將數據保存在HashMap中的正確方法是什麼?應用程序空閒時使用對象數據保持HashMap - Android
public class ApplicationCache {
private static ApplicationCache cache;
private static HashMap<String, Object> map;
private ApplicationCache(){
map = new HashMap<String, Object>();
}
public static ApplicationCache getInstance(){
if(cache == null){
cache = new ApplicationCache();
}
return cache;
}
public void setValue(String name, Object value){
map.put(name, value);
}
public Object getValue(String name){
return map.get(name);
}
public void removeValue(String name){
map.remove(name);
}
public void clear(){
map.clear();
}
}
我存儲對象爲從一個ListView中的主要活動中單擊事件的HashMap:
ApplicationCache.getInstance().setValue("details", bankList.get(position));
在另一個活動我是從這個HashMap的讀取值:
details = (DetailsVO) ApplicationCache.getInstance().getValue("details");
是否有可能通過你HashMap對象存儲SharedPreference? \ –
首選項只接受原始類型,所以你不能把一個複雜的對象在其中 – Deepak
@Deepak使HashMap的靜態 –