0

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

保存首选项方法

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

1 回答 1

4

问题只是“ýes”不等于“yes”:

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", "");
于 2012-09-03T23:56:26.490 回答