Why cannot save INT to SharedPreferences?

回眸只為那壹抹淺笑 提交于 2019-12-23 10:08:07

问题


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.


回答1:


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.




回答2:


Do you ever set a value for "Number" and "Profile"? If not then that is your problem -those strings are null.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/8900226/why-cannot-save-int-to-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!