Search code examples
javaandroidsharedpreferencesandroid-preferences

android context and sharedpreferences


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


Solution

  • But the app crashes when that it is included. But need something like that to get to sharedpreferences:

    Activity extends ContextWrapper. 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 keyword this. If you need it in a Fragment you can use getActivity() to retrieve the context of the activity that is hosting the Fragment.

    Edit:

    in your case you have to possibilities. You add a constructor that takes a Context to the AsyncTask, or you read the values in the Activity and pass it to the AsyncTask. I would recommend you the second approach