如何在不扩展任何超类的情况下获取SharedPreferences的Context



我正试图在Android中编写代码,以便从我的父类获取SharedPrefrences的上下文,而不扩展到超级类。

我的代码:

public class TestClass
{

    static Context mContext; //class variable
TestClass(Context context)
{
    mContext = context;
}
    String text = null;
    SharedPreferences pref = mContext.getApplicationContext().getSharedPreferences("Status", 0);
    text = pref.getString("Number",null);
    Log.d(" Text Result : ", text);
}

我得到错误在getApplicationContext(),没有能够找到getApplicationContext()在TestClass。

请让我知道如何获得上下文,我将使用它SharedPreferences

如果这真的是你的代码,它根本不能工作。因为全局字段将在调用构造函数之前初始化。这就是为什么

SharedPreferences pref = mContext.getApplicationContext().getSharedPreferences("Status", 0);

在构造函数初始化mContext之前被调用。

通过从Context (Activity, Service…)派生的类传入mContext字段,在初始化mContext字段之后,在构造函数中初始化您的字段

public class TestClass
{
    static Context mContext; //class variable
    String text;
    SharedPreferences pref;
    TestClass(Context context)
    {
        mContext = context;
        pref = mContext.getApplicationContext().getSharedPreferences("Status", 0);
        text = pref.getString("Number",null);
        Log.d(" Text Result : ", text);
    }
}

在Activity中调用:

TestClass tc = new TestClass(this);

首先你不能这样做(不能获得一个上下文的应用程序上下文):

SharedPreferences pref = mContext.getApplicationContext().getSharedPreferences("Status", 0);

你应该这样使用:

SharedPreferences pref = mContext.getSharedPreferences("Status",Context.MODE_PRIVATE);

另外,在没有活动的情况下使用这个没有意义?

最新更新