Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot save INT to SharedPreferences?

I have a strange problem. I have never had it before. When I try to save int value to my SharedPreference and then restore in other Activity. Value is always 0 even if I save there other value (for example: 1);

private String Number;
private String Profile;

and then saving values (in this case "1") to SharedPreferences in first Activity:

SharedPreferences a = FirstActivity.this.getSharedPreferences("a", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorProfiles = a.edit();
prefsEditorProfiles.putInt(Profile, 1);
prefsEditorProfiles.putInt(Number, 1);
prefsEditorProfiles.commit();

then restore SharedPreferences in other Activity:

SharedPreferences a = SecondActivity.this.getSharedPreferences("a", MODE_PRIVATE);
int ab = a.getInt(Number, 0);

And application shows me 0 instead of 1. My other SharedPreferences works great. I don't know where is the problem.

like image 988
Adam Avatar asked Jan 17 '12 19:01

Adam


1 Answers

I'd check what's the value of the Number and Profile variables you declared... you are using their values as keys, so if they have conflicting names, you might be overwriting one setting with the other even though the code looks right.

I'd recommend replacing this:

private String Number;
private String Profile;

With this:

private final String NUMBER = "Number";
private final String PROFILE = "Profile";

And then using those constants when setting/getting your preference value.

like image 91
Bruno Oliveira Avatar answered Sep 19 '22 05:09

Bruno Oliveira