Android SharedPreferences in Fragment

前端 未结 10 1633
萌比男神i
萌比男神i 2020-11-29 17:16

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

     SharedPreferences preferences = g         


        
相关标签:
10条回答
  • 2020-11-29 17:59

    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);
    
    0 讨论(0)
  • 2020-11-29 18:02

    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);
    }
    
    0 讨论(0)
  • 2020-11-29 18:04

    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.

    0 讨论(0)
  • 2020-11-29 18:08

    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();   
    ...   
    }
    
    0 讨论(0)
提交回复
热议问题