2012-09-03 60 views
0

我想保存輸入值,以便在應用程序重新啓動時可以調用它們。作爲指導使用this tutorial。我寫了下面的代碼,但沒有成功獲取要回收的值。任何幫助非常感謝你。如何正確實現Android的SharedPreferences?

保存首方法

public void SavePreferences(String key, String value){ 
    SharedPreferences portfoliopreferences = getPreferences(MODE_PRIVATE); 
    SharedPreferences.Editor editor = portfoliopreferences.edit(); 
    editor.putString(key, value); 
    editor.commit(); 
} 

保存首輸入

if(users.contains(usernull)){ 
    pn1 = enterportfolioname.getText().toString(); 
    denomination1 = denomination; 
    portfoliocurrency1 = portfoliocurrency; 
    user1 = new PortfolioRecord(pn1, denomination1+df.format(portfoliovalue1)); 
    users.remove(usernull); 
    users.add(user1); 
    portfoliosdelete.add(pn1); 
    adapterdeletetype.notifyDataSetChanged(); 
    portfoliolist.invalidateViews(); 
    SavePreferences("U1C", "ýes"); 
    SavePreferences("PN1", enterportfolioname.getText().toString()); 
    SavePreferences("DN1", denomination); 
    SavePreferences("PC1", "usd"); 
} 

負荷首

public void LoadPreferences(){ 
    SharedPreferences portfoliopreferences = getPreferences(MODE_PRIVATE); 
    String isuser1created = portfoliopreferences.getString("U1C", ""); 
    if(isuser1created.equals("yes")){   
     String savedportfolioname = portfoliopreferences.getString("PN1", ""); 
     String saveddenomination = portfoliopreferences.getString("DN1", ""); 
     String savedporfoliocurrency = portfoliopreferences.getString("PC1", ""); 
     pn1 = savedportfolioname; 
     denomination1 = saveddenomination; 
     portfoliocurrency1 = currencyUSD; 
     user1 = new PortfolioRecord(pn1, denomination1+portfoliovalue1);   
     users.add(user1); 
     portfoliosdelete.add(pn1); 
     calculateportfoliovalue1(); 
     adapterdeletetype.notifyDataSetChanged(); 
     portfoliolist.invalidateViews(); 
    } 
} 

回答

4

的問題很簡單,就是 「是」 不等於 「是」:

SavePreferences("U1C", "ýes"); 
... 
if(isuser1created.equals("yes")) 

所以你永遠不執行這個代碼塊內...(更改一個或其他)。


另外你創建一個新的editor,並要保存一個值,每次運行commit()。執行時,這比需要的慢。

你應該保持一類廣泛引用portfoliopreferences和來電commit()一次:

SharedPreferences.Editor editor = portfoliopreferences.edit(); 
editor.putString("U1C", "ýes"); 
editor.putString("PN1", enterportfolioname.getText().toString()); 
editor.putString("DN1", denomination); 
editor.putString("PC1", "usd"); 
editor.commit(); 

與您共創字符串到一個不使用:

String savedportfolioname = portfoliopreferences.getString("PN1", ""); 
String saveddenomination = portfoliopreferences.getString("DN1", ""); 
... 
pn1 = savedportfolioname; 
denomination1 = saveddenomination; 

您可以跳過這些:

pn1 = portfoliopreferences.getString("PN1", ""); 
denomination1 = portfoliopreferences.getString("DN1", "");