Android SharedPreferences in Fragment

Mark picture Mark · Jul 31, 2012 · Viewed 124.7k times · Source

I am trying to read SharedPreferences inside Fragment. My code is what I use to get preferences in any other Activity.

     SharedPreferences preferences = getSharedPreferences("pref", 0);

I get error

    Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper    

I have tried to follow these links but with no luck Accessing SharedPreferences through static methods and Static SharedPreferences. Thank you for any solution.

Answer

Jug6ernaut picture Jug6ernaut · Jul 31, 2012

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);