嗨,我有以下代码将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