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
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.
You can get SharedPreferences in a background thread using the PreferenceManager like this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(<YourActivity>.this);
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
.