如何正确实现Android的SharedPreferences?

时间:2012-09-03 23:49:54

标签: android sharedpreferences

我想保存输入值,以便在重新启动应用程序时可以调用它们。使用this tutorial作为指南。我编写了以下代码但是没有成功获取要调用的值。非常感谢任何帮助。谢谢。

保存偏好设置方法

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();
    }
}

1 个答案:

答案 0 :(得分:4)

问题只是“eses”不等于“是”:

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", "");