3

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?

Nermeen
  • 15,883
  • 5
  • 59
  • 72
Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141
  • Is it possible that one was a string before and you installed the new version on top of old one? – auselen Jan 24 '13 at 10:23

2 Answers2

1

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. 
Supreethks
  • 597
  • 6
  • 16
  • @auselen This usually happens while working with Preference activity. If you explicitly store a `Long` in to preference then there would be no issue. I should have added it in my original comment. – Supreethks Jan 24 '13 at 10:30
1

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.

Community
  • 1
  • 1
Nalaz
  • 11
  • 2