2016-05-10 32 views
0

這裏就是我存儲值到SharedPreferences在一個活動:檢索SharedPreferences值不起作用。任何想法我做錯了什麼?

 sharedPref = context.getSharedPreferences("sharedPref", Context.MODE_PRIVATE); 
     String firstPlace = new String("1"); 
     String secondPlace = new String("2"); 
     String thirdPlace = new String("3"); 

     editor = sharedPref.edit(); 

     editor.putString("first", firstPlace); 
     editor.putString("second", secondPlace); 
     editor.putString("third", thirdPlace); 
     editor.commit(); 

,然後嘗試檢索他們在另一個活動。然而,檢索似乎並沒有在被得到我把價值觀和只是使用默認值(因此「第一名:」「第二名」和「第三名:」用「不」結束了他們旁邊)。

SharedPreferences sharedPref = getSharedPreferences("sharedPref", MODE_PRIVATE); 

    String firstPlace = sharedPref.getString("first", "no"); 
    String secondPlace = sharedPref.getString("second", "no"); 
    String thirdlace = sharedPref.getString("third", "no"); 

    highScore1.setText("1st Place: " + firstPlace); 
    highScore2.setText("2nd Place: " + secondPlace); 
    highScore3.setText("3rd Place: " + thirdlace); 
+0

也可以加在其中創建編輯對象的代碼? – Sanoop

+0

嘗試'。適用()'不是'.commit()' – Sanoop

+0

這幾乎是所有我做編輯器...我有它在頂部「的全局變量‘SharedPreferences.Editor主編;’然後我做「editor = sharedPref.edit();」,就像你在第一個代碼塊中看到的那樣,是否還有更多的事情需要處理? – Freckles

回答

0

您可以嘗試直接把價值

editor = sharedPref.edit(); 
    editor.putString("first", "1"); 
    editor.putString("second", "2"); 
    editor.putString("third", "3"); 
0

您已經使用單獨的上下文。爲了讓你的sharedpreference可以訪問整個應用程序,你需要默認的sharedpreference。聲明如下

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

之後,您可以像以前一樣編輯和提取數據。

+0

我個人認爲使用不同的上下文不成問題。 SharedPreferences文件並不區分每個上下文,它們存儲在每個應用程序包中。 –

+0

是的,我嘗試使用DefaultSharedPreferences並沒有區別 – Freckles

0

請試試這個,

this.SharedPrefs = getSharedPreferences("MyPrefs", 0); SharedPreferences.Editor localEditor = this.SharedPrefs.edit(); localEditor.putString("first", firstPlace); localEditor.putString("second", secondPlace); localEditor.putString("third", thirdPlace); localEditor.commit(); finish();

相關問題