Search code examples
androidkotlinsharedpreferences

Unresolved reference: getPreferences


I am trying to store a boolean value which is changed every time a button is clicked. I want to do this using shared preferences, however I keep running into this error: Unresolved reference: getPreferences

This is my code:

btnStyle.setOnClickListener() {
            styleHasChanged = !styleHasChanged;

            if(styleHasChanged  == true){
                btnStyle.setText("true")
            }else{
                btnStyle.setText("false")
            }

          //  AppUtil.saveConfig(activity, config)
          //  EventBus.getDefault().post(ReloadDataEvent())

          var sharedPref : SharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
            var editor = sharedPref.edit()
            editor.putBoolean("bla", styleHasChanged)
            editor.commit()



        }

Solution

  • Is this a Fragment or an Activity? This seems code written in fragment or somewhere else. Because getPreferences() is method of activity and you need to have Activity's instance to call it .

    Just have a Activity instance and call it as below . example for Fragment:-

    btnStyle.setOnClickListener() {
            styleHasChanged = !styleHasChanged;
            if(styleHasChanged  == true){
                btnStyle.setText("true")
            }else{
                btnStyle.setText("false")
            }
            val sharedPref : SharedPreferences?= activity?.getPreferences(Context.MODE_PRIVATE);
            sharedPref?.edit()?.putBoolean("bla", styleHasChanged)?.apply()
        }