如何在不扩展任何超级类的情况下获取SharedPreferences的上下文?

问题描述 投票:-1回答:2

我想在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.

android sharedpreferences android-context
2个回答
1
投票

如果这真的是你的代码,那就完全不行了。因为在调用构造函数之前,全局字段会被初始化。这就是为什么

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

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

在你初始化了mContext字段之后,在构造函数中通过从Context派生的类(Activity, Service...)传递你的字段来初始化你的字段。

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);

1
投票

首先你不能这样做(不能获取上下文的应用上下文):

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

你应该像这样使用它。

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

另外,如果没有Activity,使用这个是没有意义的。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.