共享首选项始终返回默认值 [英] Shared Preference returns always the default value
问题描述
这是我用来在 Preference 中创建和存储值的代码.传出是字符串变量.
Here is code I am Using to create and store value in Preference. outgoing is String variable.
SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("PhoneNo","Hi");
editor.commit();
这是从 SharedPreference 获取值的代码.
Here is the code to get value from SharedPreference.
SharedPreferences sp
=getSharedPreferences(outgoing,Activity.MODE_PRIVATE);
String calln = sp.getString("PhoneNo","0");
Toast.makeText(mContext, "SHARED"+calln,Toast.LENGTH_LONG).show();
推荐答案
您可能应该在访问它们的上下文中调用 getSharedPreferences
.
You should probably call the getSharedPreferences
on the context from which you are accessing them.
因此,根据您访问上下文的方式,如果您将其传递给其他活动或异步任务,以下是一些用法示例:
Therefore, depending on how you can access your context, if you pass it to some other activity or in an asynchronous task, here are some examples of usage:
this.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
context.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
此外,一种测试内容的方法是在 SharedPreferences
更改时使用侦听器:
Also, one way you can test your stuff is to use a listener when SharedPreferences
get changed:
onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
Called when a shared preference is changed, added, or removed.
您也可以使用Preference Manager
来获取SharedPreferences
:
You can also use the Preference Manager
to obtain the SharedPreferences
:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).getString(
"PhoneNo", "0");
或者存储它们:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).edit().putString(
"PhoneNo", "Hi").commit();
这篇关于共享首选项始终返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!