not getting integer value from SharedPreference

空扰寡人 提交于 2019-12-02 06:40:27

问题


I am trying to store user id in SharedPreference in one activity and want to get this integer id in any activity.
To put this value in Shared Preference i use following code.

SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("userId", varaible);                 
prefsEditor.commit();  

Then i am trying to get this value, i use following code for this

SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    int userId = myPrefs.getInt("userId", -1);  

But it return me -1 not userId. and if i use following line to fetch integer value then it will showing runtime exception.

    int userId = myPrefs.getInt("userId", Integer(null));   

I don't understand what's wrong in my code. How to get this integer userId in my another activity.
Please give me any reference or hint.
Thanks in advance.


回答1:


Change this:

SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
int userId = myPrefs.getInt("userId", -1);  

to this

SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
int userId = myPrefs.getInt("userId", 0);  

it should work that way.




回答2:


There is nothing wrong with your code and I tested this exact case and it is working perfectly. For sure you can use the default value as -1.

Do you have both activities in the same application?

What I can suggest for debugging is to make sure that your application runs in the sequence you expect and that the value is stored correctly. You can try to retrieve it directly after storing it within the same activity.



来源:https://stackoverflow.com/questions/14153286/not-getting-integer-value-from-sharedpreference

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