Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SharedPreferences in Fragment

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.

like image 955
Mark Avatar asked Jul 31 '12 13:07

Mark


People also ask

Can we use 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!

Where are Android SharedPreferences stored?

Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment. getDataDirectory() .

Is SharedPreferences Singleton?

There are 2 templates and samples: SharedPreferences Singleton that uses String keys. SharedPreferences Single that uses Enum keys.

Can we use SharedPreferences in Android?

Use SharedPreferences in Android if you want to store simple data like name, phone number, age, email, last opened screen... We are going to talk about SharedPreferences in Android. It is a place where you can store data; this is an XML file with values stored in it.


2 Answers

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); 
like image 107
Jug6ernaut Avatar answered Sep 21 '22 21:09

Jug6ernaut


The marked answer didn't work for me, I had to use

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 

EDIT:

Or just try removing the this:

SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE); 
like image 35
Leon Avatar answered Sep 22 '22 21:09

Leon