user2101081
user2101081

Reputation: 451

Android java.lang.Long cannot be cast to java.lang.String

Okay so I am storing a long in my shared preferences using

e.putLong("startTime", SystemClock.uptimeMillis());

and I am getting it from share preferences like

SHARED_PREFS = context.getSharedPreferences(LOCAL_PREF, MODE_PRIVATE);
long startTime = SHARED_PREFS.getLong("startTime", 0L); <-- Stack trace points to this line.

but I am getting this error on some devices and not sure why, I am not trying to cast it to a String at all.

java.lang.Long cannot be cast to java.lang.String

Everything I find points towards trying to set this as a String value and I am not trying to do that at all, I am trying to use the long value directly.

** UPDATE STACK TRACE **

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
        at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:255)
        at com.tech.utility.Tools.refreshPrefs(Tools.java:193)
        at com.tech.activity.Menu_dashboard.onStart(Menu_dashboard.java:762)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1340)
        at android.app.Activity.performStart(Activity.java:7191)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2920)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
        at android.app.ActivityThread.-wrap11(Unknown)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6940)
        at java.lang.reflect.Method.invoke(Method.java:-2)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Upvotes: 0

Views: 1315

Answers (2)

Catherine Catherine
Catherine Catherine

Reputation: 11

This is a bit late, but for those who are still facing this problem, just overwrite this value in SharedPreferences with the value in the type you need before calling the get method. Perhaps a String (or other type) was written there before

Upvotes: 1

Matt Clark
Matt Clark

Reputation: 28589

If you were to read the docs you would read that the getLong method will:

Throws ClassCastException if there is a preference with this name that is not a long.

So, somewhere else in the app, you must have called:

e.putLong("startTime", "someString");

Upvotes: 2

Related Questions