mducc
mducc

Reputation: 743

Integer cannot be cast to Boolean when use Preferences

I use Preferences in Android. When i change a switch, i put a boolean:

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)

switch1.setOnCheckedChangeListener{_, isChecked ->
        if(isChecked){
            sharedPref?.let {
                with(it.edit()) {
                    putBoolean("sw1", true)
                    apply()
                }
            }
        }else{
            sharedPref?.let {
                with(it.edit()) {
                    putBoolean("sw1", false)
                    apply()
                }
            }
        }
    }

And i get it:

val sw1 = sharedPref?.getBoolean("sw1", false)
sw1?.let {
        switch1.isChecked = sw1
    }

But i receive a error:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Boolean

Upvotes: 1

Views: 1050

Answers (1)

Bharath Kumar
Bharath Kumar

Reputation: 541

If data in shared preferences is stored using putInt() and getBoolean() is used to retrieve the data for same key, then ClassCastException will occur.

It can be solved in 2 ways.

  1. The shared preferences data can be cleared. From Settings->App info-> Your app -> Clear Data.

  2. In case there is a need to change the preferences data type to boolean then make sure that putBoolean() is called before getBoolean().

Upvotes: 2

Related Questions