Reputation: 111
I'm trying to store and retrieve numbers in android so later I can do calculations on the results. I am managing to store and get strings but for some reason can't seem to get it to work for integers
here is the string code I tested
save...
getSharedPreferences("words", 0).edit().putString("YAS", wordString).commit();
receive...
String words= getSharedPreferences("words", 0).getString("YAS", "");
t.setText(words);
but when I try a similar thing with integers it doesn't work.
save...
getSharedPreferences("number", 0).edit().putInt("numbers", 1).commit();
receive...
int test2 = getSharedPreferences("number", 0).getInt("numbers",0);
Basically I need the saved variable to be 0 before the button is pressed (which I'm guessing it will be since it doesn't exist at that point) and then change to 1 when pressed. No matter how many times the button is pressed it will only ever equal 1 cheers for any help
Upvotes: 1
Views: 1646
Reputation: 189594
From you comment I assume that you are doing something like this:
int test2 = getSharedPreferences("number", 0).getInt("numbers",0);
t.setText(test2);
This will make the system look for a ressource in your xml ressource files with ressource id with the value test2 (0 in your case). This ressource will not exist and you get an exception.
Use
int test2 = getSharedPreferences("number", 0).getInt("numbers",0);
t.setText(Integer.toString(test2));
instead.
Upvotes: 5
Reputation: 23982
You wrong at that point that SharedPrefereces doesn't exist before button is pressed. At the first time - yes, it doesn't exists. But when you're saved your value it will be there, no matter how many times you restarted the application. However, if you delete your app then SharedPrefereces will be deleted too.
Looks like that you should use a simple integer variable (class field, for example).
Upvotes: 0