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;
}
}
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.
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() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With