Unresolved reference: getPreferences

Viewed 5177

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()



        }
3 Answers

For KOTLIN

If Activity then use this@ActivityName

var sharedPref : SharedPreferences = this@ActivityName.getPreferences(Context.MODE_PRIVATE);

If Fragment then use activity!!

var sharedPref : SharedPreferences = activity!!.getPreferences(Context.MODE_PRIVATE);

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()
    }

Try to open sharedPreferences via application context, like this:

application.getSharedPreferences("Your preference name", Context.MODE_PRIVATE)

All you need is context for opening preferences.

Related