可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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);
回答2:
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);
回答3:
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.
回答4:
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);
}
回答5:
This did the trick for me
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs
回答6:
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();
...
}