嗨,我有以下代碼將arraylist存儲到列表中,然後將其保存到SharedPreference中。但是當我重新運行應用程序時,這些值都消失了,無論我多少次調用將更多元素添加到數組列表中,它只會調用一次。 以下是我的代碼:SharedPreferences提交後未保存
//debug usage
Button z = (Button)findViewById(R.id.button3);
z.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
testres.add("1");
testres.add("2");
testres.add("3");
}
});
SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
set.addAll(testres);
edit.putStringSet("yourKey", set);
edit.commit();
這也是我如何檢索:
SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);
Set<String> set = prefs.getStringSet("yourKey", null);
List<String> sample= new ArrayList<String>(set);
testres = new ArrayList<String> (set);
for(int i =0; i<testres.size();i++){
System.out.println("Printing: "+testres.get(i));
}
無論我有多少次調用的onclick,該testres將只有1,2,3 ArrayList中如果我重新啓動應用程序,arraylist中的元素不見了。請指教非常感謝!
更新:我設法根據下面的答案檢索我的值,但仍然無法將更多元素添加到數組列表中。數組列表卡住元素1,2,3。建議。
嘗試。適用(),而不是提交 – Eyeball 2015-02-09 04:22:51
通過重新啓動,你的意思是,從Eclipse在調試/運行模式,重新部署或退出應用程序,並從啓動開始? – 2015-02-09 04:22:54
@Eyeball已嘗試並且無法正常工作。=/ – Gene 2015-02-09 04:45:51