问题描述
我有四个Activities
:MainActivity
,HomeActivity
,SecondActivity
,ThirdActivity
.
我正在使用MainActivity
作为欢迎屏幕,我的应用程序始于HomeActivity.我在HomeActivity
中定义了SharedPreferences
:
I'm using the MainActivity
as a welcome screen and my app beginns at HomeActivity. I defined my SharedPreferences
in HomeActivity
:
外部OnCreate
方法:
Outside OnCreate
method:
SharedPreferences settings;
SharedPreferences.Editor editor;
在OnCreate
内部:
And inside OnCreate
:
settings = getSharedPreferences("app_settings", Context.MODE_APPEND);
editor = settings.edit();
我的问题是我的SharedPreferences
仅在HomeActivity
中工作.我也想在SecondActivity
中打电话给我的sharedPreferences
.
My Problem is that my SharedPreferences
only works in HomeActivity
.I want to call my sharedPreferences
in SecondActivity
as well.
我该怎么办?
推荐答案
您可以使用SharedPreferences这样实现单例
You can implement a singleton with SharedPreferences like this
public class SPManager {
private static final String TAG = SPManager.class.getName();
private static SPManager instance;
private Context mContext;
private SharedPreferences mPrefs;
private static final String PREF_NAME = "com.package.app";
private static final String KEY_NAME = "user_name";
public static SPManager getInstance(Context context) {
if (instance == null) {
instance = new SPManager(context);
}
return instance;
}
private SPManager(Context context) {
mContext = context;
mPrefs = mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
// Example
public void addName(String name) {
mPrefs.edit().putString(KEY_NAME, name).apply();
}
public String getName() {
return mPrefs.getString(KEY_NAME, "John Doe");
}
}
您也可以像这样使用此单例:SPManager.getInstance(context).getName();
Also you can use this singleton like that : SPManager.getInstance(context).getName();
使用和更新它都很简单.
It's simple to use and update it.
希望能为您提供帮助.
这篇关于我应该在MainActivity中定义SharedPreferences吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!