Reputation: 931
I want to save input values so that they can be recalled when the application is restarted. Using this tutorial as a guide. I wrote the following code but am not having success getting the values to be recalled. Any help is greatly appreciated thank you.
Save Preferences method
public void SavePreferences(String key, String value){
SharedPreferences portfoliopreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = portfoliopreferences.edit();
editor.putString(key, value);
editor.commit();
}
Save Preferences input
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");
}
Load Preferences
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();
}
}
Upvotes: 0
Views: 293
Reputation: 86958
The problem is simply that "ýes" does not equal "yes":
SavePreferences("U1C", "ýes");
...
if(isuser1created.equals("yes"))
So you never execute the code inside this block... (Change one or the other.)
Also you create a new editor
and run commit()
each time you want to save one value. While it executes, this is slower than necessary.
You should keep a class wide reference to portfoliopreferences
and only call commit()
once:
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();
And you create Strings to that one don't use:
String savedportfolioname = portfoliopreferences.getString("PN1", "");
String saveddenomination = portfoliopreferences.getString("DN1", "");
...
pn1 = savedportfolioname;
denomination1 = saveddenomination;
You can skip over these:
pn1 = portfoliopreferences.getString("PN1", "");
denomination1 = portfoliopreferences.getString("DN1", "");
Upvotes: 4