2015-02-09 93 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