How do I get sharedpreferences in Asynctask?

前端 未结 3 2006
心在旅途
心在旅途 2020-12-19 04:40

I am writing an android application for my school project but i am stuck here. The problem is i have to access a SharedPreferences value and need it in an

3条回答
  •  渐次进展
    2020-12-19 04:52

    You can get SharedPreferences in the background using an 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 this refers to the AsyncTask instance that you are calling if from.


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

        new AsyncTask()
        {
            @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, this refers to the Activity or Service that I call this from.

提交回复
热议问题