I am trying to read SharedPreferences inside Fragment. My code is what I use to get preferences in any other Activity.
SharedPreferences preferences = g
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);
You can make the SharedPrefences
in onAttach
method of fragment like this:
@Override
public void onAttach(Context context) {
super.onAttach(context);
SharedPreferences preferences = context.getSharedPreferences("pref", 0);
}
As a note of caution this answer provided by the user above me is correct.
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.
getActivity()
and onAttach()
didnot help me in same situation
maybe I did something wrong
but! I found another decision
I have created a field Context thisContext
inside my Fragment
And got a current context from method onCreateView
and now I can work with shared pref from fragment
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
thisContext = container.getContext();
...
}