Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class cast exception on shared preferences

Tags:

android

I got a property, persisted in shared prferences.

there are 2 places refer to it in entire code:

firstRunTimestamp = wmbPreference.getLong(ApplicationData.ParametersInternals.FIRST_RUN_DATE, 0);

editor.putLong(ApplicationData.ParametersInternals.FIRST_RUN_DATE, new Date().getTime());

In my logs I found this exception

"java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long at android.app.SharedPreferencesImpl.getLong("

And the stack indicates this code is inside the method that access this property, Can anyone explaing how it is even possible?

like image 700
Chen Kinnrot Avatar asked Dec 20 '25 02:12

Chen Kinnrot


2 Answers

SharedPreference stores all the data in the form of key value pairs. Both key and values being string. (This is not true if you explicitly store values to the SharedPreference as Long. Check my reply to below.)

You need to parse the Long value from your string as

firstRunTimestamp = Long.parseLong(wmbPreference.getString(ApplicationData.ParametersInternals.FIRST_RUN_DATE, "0")); //Notice here, the default value is also made a string. 
like image 129
Supreethks Avatar answered Dec 22 '25 17:12

Supreethks


Check if you don't have a preference with the same key value in your preference.xml. Note that preferences defined in preference.xml are always stored as String values.


Another solution - if you first define a preference key as a int from runtime and later on you decide to define the same key as a String, it can cast a ClassCastExcepion, although you've changed your code. This is because this key figures in shared preferences file as a Int. To avoid this delete shared preferences file, from your code or from your device depending on needs and reinstall your app.

like image 43
Nalaz Avatar answered Dec 22 '25 17:12

Nalaz