3

我得到了一个财产,坚持共同的偏好。

整个代码中有两个地方引用它:

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

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

在我的日志中我发现了这个异常

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

并且堆栈表明此代码在访问此属性的方法中,任何人都可以解释它是如何可能的吗?

4

2 回答 2

1

SharedPreference以键值对的形式存储所有数据。键和值都是字符串。(如果您将 SharedPreference 的值显式存储为 Long,则情况并非如此。请查看我对下面的回复。)

您需要将字符串中的 Long 值解析为

firstRunTimestamp = Long.parseLong(wmbPreference.getString(ApplicationData.ParametersInternals.FIRST_RUN_DATE, "0")); //Notice here, the default value is also made a string. 
于 2013-01-24T10:15:40.770 回答
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.

于 2016-06-18T14:30:34.207 回答