Long cannot be cast to java.lang.Integer SharedPreference

Viewed 207

A very simple piece of code that returns me sometimes a ClassCastException. There is nowhere in my code a place where I have saved Long into this property.

Fatal Exception: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
   at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:307)

Maybe someone has an idea why does it happen?

var numberOfRepayment
    get() = sharedPrefs.getInt(UserSetting.NUMBER_OF_REPAYMENT.value, 0)
    set(value) {
        editor.run { putInt(UserSetting.NUMBER_OF_REPAYMENT.value, value).apply() }
    }

I have never personally met this issue but see it through Crashlytics

1 Answers

I just have experienced a similar problem. What I figured about it was a duplicate key as @Tenfour04 suggested in a comment.

In my case, int cannot be cast to Long error was occurring.

Caused by java.lang.ClassCastException
    java.lang.Integer cannot be cast to java.lang.Long
    android.app.SharedPreferencesImpl.getLong (SharedPreferencesImpl.java:315)

At last, I found that my app used the same key as int once (and now I would use it as Long).

So, I solved my problem simply by changing the key name.

Related