Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get sharedpreferences in Asynctask?

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

}
like image 829
user3316779 Avatar asked May 11 '14 19:05

user3316779


People also ask

How do I create a SharedPreferences file?

You can create a new shared preference file or access an existing one by calling one of these methods: getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.

Where are SharedPreferences stored in Android?

Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment. getDataDirectory() .


1 Answers

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.

like image 85
Green goblin Avatar answered Oct 03 '22 06:10

Green goblin