Wun
Wun

Reputation: 6381

Why the HashSet cannot be cast to java.lang.String happened in save arraylist to SharedPreferences in Android?

I try to use the following code to set and get the ArrayList to/from SharedPreferences. But it show the following error when I call getSharedPreferencesMutableList:

Caused by java.lang.ClassCastException
java.util.HashSet cannot be cast to java.lang.String
com.bbin.authenticator.Support.sharedPreference.SharedPreferenceHelper.getSharedPreferencesMutableList

The code is like the following:

fun setSharedPreferencesMutableList(context: Context, setName: String, value: ArrayList<String>) {
    var gson = Gson()
    var json = gson.toJson(value)

    val setting = context.getSharedPreferences(UBAuth, Context.MODE_PRIVATE)
    setting.edit().putString(setName, json).apply()

}

fun getSharedPreferencesMutableList(context: Context, getName: String): ArrayList<String> {
    val setting = context.getSharedPreferences(UBAuth, Context.MODE_PRIVATE)
    var json = setting.getString(getName,"")
    var type = object : TypeToken<List<String>>() {}.type
    var list = Gson().fromJson<ArrayList<String>>(json, type)

    if(list != null){
        return list
    }else{
        return ArrayList<String>()
    }
}

I did not set anything to SharedPreferences for calling setSharedPreferencesMutableList. So the value is empty.

Why it show this error? Did I missing something ?

Upvotes: 1

Views: 2418

Answers (1)

ismail alaoui
ismail alaoui

Reputation: 6063

the reason is you have a Shared Preferences with a key that is not a String.

The documentation says that in this case a ClassCastException is thrown

Upvotes: 2

Related Questions