How to resolve an error: getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){}

前端 未结 2 696
走了就别回头了
走了就别回头了 2021-02-06 18:14

I\'m getting this error in my coding and not entirely sure how to resolve this. I\'ve searched to try and resolve this issue but can\'t seem to find anything that works. I\'ve

相关标签:
2条回答
  • 2021-02-06 18:49

    The error means that there is no getSharedPreferences method in View class, because getSharedPreferences is a method of Context class. In order to access getSharedPreferences method inside View class you need to provide it with an instance of Context class. Something like:

    //Instance of Context 
    Context pref;
    
    SharedPreferences sharedPref = pref.getSharedPreferences(PREFRENCES_NAME,0);
    

    Note: Context pref & String PREFRENCES_NAME should not be null;

    0 讨论(0)
  • 2021-02-06 18:55

    Change this code :

    SharedPreferences pref = getSharedPreferences(PREFRENCES_NAME,0);
    

    To :

    SharedPreferences pref = getActivity().getSharedPreferences(PREFRENCES_NAME,0);
    

    Remember you cant call getSharedPreferences method directly from Fragment, because it belongs to the Activity class. Hence, you just need to call getActivity.

    0 讨论(0)
提交回复
热议问题