Vasko Vasilev
Vasko Vasilev

Reputation: 574

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



        }

Upvotes: 5

Views: 7991

Answers (4)

alinton gutierrez
alinton gutierrez

Reputation: 630

my solution for kotlin is:

//declarate in your class
 private lateinit var sharedpreferences: SharedPreferences
const val TOKEN_KEY = "token"



//declarate inside onCreate of activity
 sharedpreferences = requireContext().getSharedPreferences(SHARED_PREFS,Context.MODE_PRIVATE);

//get token_activo storage in android       
 token_activo = sharedpreferences.getString(TOKEN_KEY, null)

//save in android
 val editor = sharedpreferences.edit()
  editor.putString(TOKEN_KEY, "value_to_save")
  editor.apply()

Upvotes: 0

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

For KOTLIN

If Activity then use this@ActivityName

var sharedPref : SharedPreferences = [email protected](Context.MODE_PRIVATE);

If Fragment then use activity!!

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

Upvotes: 14

SpiritCrusher
SpiritCrusher

Reputation: 21043

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

Upvotes: 6

Dmytro Ivanov
Dmytro Ivanov

Reputation: 1310

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.

Upvotes: 1

Related Questions