How do I get sharedpreferences in Asynctask?

12,238

Solution 1

Override onPreExecute or onPostExecute method of AsyncTask and get SharedPreferences there:

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

Please note that getSharedPreferences is an Activity method. So, you need to call it through Context if you are not using it in Activity.

Solution 2

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

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

Solution 3

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<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, this refers to the Activity or Service that I call this from.

Share:
12,238
user3316779
Author by

user3316779

Updated on June 11, 2022

Comments

  • user3316779
    user3316779 almost 2 years

    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 AsyncTask class. When I try to access it, it wont let me because of the context. How can i reach my SharedPreferences in my AsyncTask?

    public class CheckAccess extends AsyncTask<JSONObject, Integer, Boolean>{
    
    
        @Override
        protected Boolean doInBackground(JSONObject... params) {
    
            //Trying to get sharedpreferences here wont work.
    
            return null;
        }
    
    }
    
  • user3316779
    user3316779 about 10 years
    Good idea, but i am having trouble with getting it. How to continue this line in preExecute? SharedPreferences prefs = ...
  • user3316779
    user3316779 about 10 years
    I think the problem is that i don't call it through Context since i am not using it in an activity. How can i do it?
  • Alejandro Alcalde
    Alejandro Alcalde about 10 years
    Simply pass the context to the AsynTask constructor.
  • Alejandro Alcalde
    Alejandro Alcalde about 10 years
    Then you can not get the preferences I think. You need the Activity
  • Green goblin
    Green goblin about 10 years
    You must be using the AsynTask class from an activity. Before calling it, call the constructor of class where Asynctask is residing. In the constructor, pass the context.
  • user3316779
    user3316779 about 10 years
    I am using it like this: jsonObject = new GetData().execute(cardId).get(); What changes do i need?
  • Green goblin
    Green goblin about 10 years
    Define a constructor of CheckAccess to accept Context. In the constructor definition, initialize Context. Pass the Context while creating object.
  • Richard Le Mesurier
    Richard Le Mesurier over 9 years
  • Green goblin
    Green goblin over 9 years
    @RichardLeMesurier: Thanks for correcting me. I totally missed it. I have corrected my answer