I am trying to get context to run async sharedpreferences. Tried to get context with:
public class MainActivity2 extends Activity implements OnClickListener {
public MainActivity2(final Context context) {
this.context = context;
}
private Context context;
//....rest of class.....
}
But the app crashes when that it is included. But need something like that to get to sharedpreferences:
class CreateUser extends AsyncTask<String, String, String> {
// .....rest of ....
@Override
protected String doInBackground(String... args) {
SharedPreferences prefs = android.preference.PreferenceManager.getDefaultSharedPreferences(context);
String myIntegerValue = prefs.getString("ok", "f");
android.util.Log.d("your_tag", "myint: " + myIntegerValue);
}
//rest of.....
}
trying to get sharedpreferences like this does not work:
SharedPreferences prefs = android.preference.PreferenceManager.getDefaultSharedPreferences(getactivity());
trying to get sharedpreferences like this does not work:
SharedPreferences prefs = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
getDefaultSharedPreferences cannot be applied to MainActivity2.CreateUser when using this
just use ur Activity as Context MainActivity.this should do the trick
Activity
extendsContextWrapper
. You don't need (and you can't have it) the constructor that takes a context as parameter. Your context in the activity is the keywordthis
. If you need it in a Fragment you can usegetActivity()
to retrieve the context of the activity that is hosting theFragment
.Edit:
in your case you have to possibilities. You add a constructor that takes a
Context
to theAsyncTask
, or you read the values in the Activity and pass it to theAsyncTask
. I would recommend you the second approachwhile using shared preferences in asynctask you should in onPreExecute method get all data from sharedprefs to your local variable, use them inside doInBackground and if needed update those values, do it in onPostExecute.
You don't need to explicitly declare context anywhere if u are using asynctask in same class. you can just write Classname.this.
Better way to implement it is initialize your sharedprefs in oncreate as u can use it anywhere.
In case if you are writing aynctask in different class then you can write a function which will accept context and will call asynctask to get executed.
Try this:
or