Unresolved reference: getPreferences

不问归期 提交于 2019-12-24 01:01:37

问题


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



        }

回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/56662832/unresolved-reference-getpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!