Java 如何在 Asynctask 中获取共享首选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23596903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:13:32  来源:igfitidea点击:

How do I get sharedpreferences in Asynctask?

javaandroidandroid-asynctasksharedpreferences

提问by user3316779

I am writing an android application for my school project but i am stuck here. The problem is i have to access a SharedPreferencesvalue and need it in an AsyncTaskclass. When I try to access it, it wont let me because of the context. How can i reach my SharedPreferencesin my AsyncTask?

我正在为我的学校项目编写一个 android 应用程序,但我被困在这里。问题是我必须访问一个SharedPreferences值并在AsyncTask类中需要它。当我尝试访问它时,它不会让我因为上下文。我怎样才能达到我SharedPreferencesAsyncTask

public class CheckAccess extends AsyncTask<JSONObject, Integer, Boolean>{


    @Override
    protected Boolean doInBackground(JSONObject... params) {

        //Trying to get sharedpreferences here wont work.

        return null;
    }

}

采纳答案by Green goblin

Override onPreExecuteor onPostExecutemethod of AsyncTaskand get SharedPreferencesthere:

覆盖onPreExecuteonPostExecute方法AsyncTask并到达SharedPreferences那里:

@Override
protected void onPreExecute() {
    super.onPreExecute();
    //get sharedPreferences here
    SharedPreferences sharedPreferences = getSharedPreferences(<SharedPreferencesName>, <Mode>);
}

Please note that getSharedPreferencesis an Activitymethod. So, you need to call it through Contextif you are not using it in Activity.

请注意,这getSharedPreferences是一种Activity方法。因此,Context如果您不在Activity.

回答by tlahoda

You can get SharedPreferences in a background thread using the PreferenceManager like this:

您可以使用 PreferenceManager 在后台线程中获取 SharedPreferences,如下所示:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(<YourActivity>.this);

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(<YourActivity>.this);

回答by Richard Le Mesurier

You can get SharedPreferencesin the background using an AsyncTask.

您可以SharedPreferences使用AsyncTask.

The mistake is in this line, where you are passing in the wrong type of variable:

错误在于这一行,您传入了错误类型的变量:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

In your case, the word thisrefers to the AsyncTaskinstance that you are calling if from.

在您的情况下,该词this指的AsyncTask是您正在调用的实例。



What I do is I pass the Contextin to the task in the execute()method. See the code below for a working example:

我所做的是将Contextin传递给方法中的任务execute()。有关工作示例,请参阅下面的代码:

    new AsyncTask<Context, Void, String>()
    {
        @Override
        protected String doInBackground(Context... params)
        {
            Context context = params[0];
            SharedPreferences prefs =
                    context.getSharedPreferences("name of shared preferences file",
                            Context.MODE_PRIVATE);

            String myBackgroundPreference = prefs.getString("preference name", "default value");

            return myBackgroundPreference;
        }

        protected void onPostExecute(String result)
        {
            Log.d("mobiRic", "Preference received in background: " + result);
        };

    }.execute(this);

In the above example, thisrefers to the Activityor Servicethat I call this from.

在上面的例子中,this指的是我称之为的ActivityService