Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android SharedReference所需的上下文_Android_Sharedpreferences_Android Context - Fatal编程技术网

Android SharedReference所需的上下文

Android SharedReference所需的上下文,android,sharedpreferences,android-context,Android,Sharedpreferences,Android Context,我正在asynctask中使用SharedReferences,但由于此原因,以下代码行无法工作: SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); 但是,如果我删除“this”,它会抛出以下错误: 09-04 10:16:49.184: E/AndroidRuntime(1883): at android.content.ContextWrappe

我正在asynctask中使用SharedReferences,但由于此原因,以下代码行无法工作:

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
但是,如果我删除“this”,它会抛出以下错误:

09-04 10:16:49.184: E/AndroidRuntime(1883):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:161)

而且,如果这使事情变得更复杂,它是从服务调用的吗?那么,如何为这个SharedReferences提供适当的上下文呢?

在扩展活动的类中全局声明它

 public static SharedPreferences prefs;
   pref=PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 

现在您可以根据需要使用
pref

在扩展活动的类中全局声明它

 public static SharedPreferences prefs;
   pref=PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 

现在您可以根据需要使用
pref

您可以在AsyncTask构造函数中设置一个参数,该参数将作为基本上下文,如下所示:

public class X extends AsyncTask {

    private Context context;

    public X(Context context) {
        this.context = context;
    }

    @Override
    doInBackground() {
        SharedPreferences prefs = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
        // your code
    }

Hugs.

您可以在AsyncTask构造函数中设置一个参数,该参数将作为基本上下文,如下所示:

public class X extends AsyncTask {

    private Context context;

    public X(Context context) {
        this.context = context;
    }

    @Override
    doInBackground() {
        SharedPreferences prefs = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
        // your code
    }

Hugs.

使用扩展活动的类this,如MainActivity。thisPs:您应该包括在没有
this
的情况下得到的整个错误。您只需要应用程序的上下文即可访问共享引用。如果您需要从活动外部使用它,我建议您创建一个应用程序类,并在需要时从那里使用上下文。啊!!该服务有自己的上下文-您可以使用它。为
上下文创建全局变量
,并在整个活动中使用该
上下文
。使用该类扩展活动,如MainActivity。thisPs:您应该包括在没有
this
的情况下发生的整个错误。您只需要应用程序的上下文即可访问共享参考。如果您需要从活动外部使用它,我建议您创建一个应用程序类,并在需要时从那里使用上下文。啊!!该服务有自己的上下文-您可以使用它。为
上下文
创建全局变量,并在整个活动中使用该
上下文
,这也是一个好点,+1表示有效的备选答案:)这也是一个好点,+1表示有效的备选答案:)