Domanda

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

}
È stato utile?

Soluzione

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.

Altri suggerimenti

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

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

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top