从不同的活动共享preferences [英] SharedPreferences from different activity
问题描述
我从活动的负载共享preferences以下列方式:
I load from activity A the SharedPreferences in following way:
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
在活动BI要加载的共享preferences。下面是一个NullPointerException异常:
At activity B I want to load the SharedPreferences. Following was a NullPointerException:
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
data = sharedPreferences.getString("name", "08:00") ;
}
如果我尝试下,我得到这个编译错误:A型没有封闭实例是在范围访问
If I try following, I get this compilation error: "No enclosing instance of the type A is accessible in scope"
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(A.this);
data = sharedPreferences.getString("name", "08:00") ;
}
我怎样才能访问这些数据?
How can I access the data?
推荐答案
使用 getApplicationContext()
而不是这
在这两个行业为:
use getApplicationContext()
instead of this
in both Activities as:
在活性的共享preferences以下列方式:
In activity A the SharedPreferences in following way:
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
Intent sd=new Intent(this,Secongtess.class);
startActivity(sd);
}
而在b活动获得价值为:
and in Activity B get Value as:
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString("name", "08:00") ;
Toast.makeText(this,data, Toast.LENGTH_LONG).show();
}
因为作为医生说:
because as doc says:
<一个href="http://developer.android.com/reference/android/$p$pference/$p$pferenceManager.html#getDefaultShared$p$pferences%28android.content.Context%29">getDefaultShared$p$pferences(Context上下文):
获取一个共享preferences实例指向缺省文件 在给定的上下文中使用的由preference框架
Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.
这篇关于从不同的活动共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!