Android SharedPreferences in Fragment

The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work…because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).

So you have to get your applications Context by

// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

Leave a Comment