Reputation: 2192
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.
Upvotes: 5
Views: 3085
Reputation: 1501
I've been trying for a while to use putInt
like you but it always give an error.
prefsEditorProfiles.putInt(Number, 1);
by just changing a.putInt
to a.putString
and retrieving it with a.getString
I was able to have the correct value.
so, I guess there should be something wrong with putInt
and getInt
.
Anyway, try that also to have the correct value you need to continue for application.
Upvotes: 1
Reputation: 2380
Please try to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
rather than using
SharedPreferences prefs = getActivity().getSharedPreferences ("PREFS_KEY", 0);
when Storing int in shared preference
Upvotes: 1
Reputation: 5076
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.
Upvotes: 5
Reputation: 12527
Do you ever set a value for "Number" and "Profile"? If not then that is your problem -those strings are null.
Upvotes: 1