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.
You can make the
SharedPrefences
inonAttach
method of fragment like this:This did the trick for me
Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs
As a note of caution this answer provided by the user above me is correct.
However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.
The marked answer didn't work for me, I had to use
EDIT:
Or just try removing the
this
:The method
getSharedPreferences
is a method of theContext
object, so just calling getSharedPreferences from aFragment
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
getActivity()
andonAttach()
didnot help me in same situationmaybe I did something wrong
but! I found another decision
I have created a field
Context thisContext
inside my FragmentAnd got a current context from method onCreateView
and now I can work with shared pref from fragment