2015-02-09 90 views
0

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

+0

尝试。适用(),而不是提交 – Eyeball 2015-02-09 04:22:51

+0

通过重新启动,你的意思是,从Eclipse在调试/运行模式,重新部署或退出应用程序,并从启动开始? – 2015-02-09 04:22:54

+0

@Eyeball已尝试并且无法正常工作。=/ – Gene 2015-02-09 04:45:51

回答

2

不管有多少次我调用的onclick,该testres将只有 1,2,3 ArrayList中,如果我重新启动应用程序

,因为你在SharedPreferences节约价值活动开始,只保存ArrayList与默认值。

要保存testres您已在按钮上添加的项目,请在ArrayList中添加项目之后,在onClick方法内使用SharedPreferences相关代码。

 @Override 
     public void onClick(View arg0) { 
      testres.add("1"); 
      testres.add("2"); 
      testres.add("3"); 
      //... save testres ArrayList in SharedPreferences here 
     } 
+0

嗨,谢谢你的回答。是的,我无法在执行上述建议之后检索启动应用程序时的值,但无论如何无法将更多元素添加到我的数组列表中,无论调用多少个onclick。你有什么建议吗? – Gene 2015-02-09 04:44:08

+0

@Gene:在SharedPreferences中添加的列表中添加更多项目。首先你需要从ArrayList中的'SharedPreferences'中获得所有的值,然后在你从'SharedPreferences'中检索到的ArrayList中添加其他项。让我知道你是否有任何困惑? – 2015-02-09 04:46:04

+0

嗨,我相信我通过列表样品=新ArrayList (集); testres = new ArrayList (set);我做错了吗? – Gene 2015-02-09 04:49:16

0
SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE); 
SharedPreferences.Editor edit=prefs.edit(); 


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"); 
     Set<String> set = new HashSet<String>(); 
set.addAll(testres); 
edit.putStringSet("yourKey", set); 
edit.commit(); 
    } 
}); 
+0

嗨,谢谢你的回答。是的,无法在启动应用程序时检索我的值,但是无论调用多少个onclick,我都无法将更多元素添加到我的数组列表中。你有什么建议吗? – Gene 2015-02-09 04:43:44