我应该在MainActivity中定义SharedPreferences吗? [英] Should I define SharedPreferences in the MainActivity?

查看:118
本文介绍了我应该在MainActivity中定义SharedPreferences吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个Activities:MainActivityHomeActivitySecondActivityThirdActivity.

我正在使用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吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆