问题描述
我正在尝试将用户 ID 存储在一个活动的 SharedPreference 中,并希望在任何活动中获取此整数 ID.
将此值放入共享首选项中,我使用以下代码.
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);
但它返回给我 -1 而不是 userId.如果我使用以下行来获取整数值,那么它将显示运行时异常.
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));
我不明白我的代码有什么问题.如何在我的另一个活动中获取这个整数 userId.
请给我任何参考或提示.
提前致谢.
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.
推荐答案
改变这个:
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
int userId = myPrefs.getInt("userId", -1);
到这里
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
int userId = myPrefs.getInt("userId", 0);
它应该这样工作.
这篇关于没有从 SharedPreference 获取整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!