4

所以有一种方法getLong()SharedPreferences没有办法<long-array>strings.xml. 那么在什么情况下我们使用geLong()?

strings.xml

<string-array name="intervals">
    <item>Never</item>
    <item>Minute</item>
    <item>Fifteen</item>
    <item>Half hour</item>
    <item>An hour</item>
    <item>Half day</item>
    <item>Day</item>
</string-array>
<string-array name="intervalValue">
    <item>0</item>
    <item>60000</item>
    <item>900000</item>
    <item>1800000</item>
    <item>3600000</item>
    <item>86400000</item>
</string-array>

Preferences.xml

<ListPreference
    android:entries="@array/intervals"
    android:entryValues="@array/intervalValue"
    android:key="interval"
    android:summary="@string/summaryUpdaterInterval"
    android:title="@string/titleUpdaterInterval" >

代码:

public long getInterval()
{
    return prefs.getLong("interval", INTERVAL_NEVER);
}

原因:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long

4

2 回答 2

0

尝试

return Long.valueOf(prefs.getString("interval", INTERVAL_NEVER));
于 2013-07-27T18:49:57.797 回答
0

尝试使用:

public long getInterval()
{
    return Long.valueOf(prefs.getString("interval", INTERVAL_NEVER));
}

或者那个:

public long getInterval()
{
    long value = INTERVAL_NEVER;
    try
    {
        value = Long.parseLong(prefs.getString("interval", "" + INTERVAL_NEVER));
    } catch (Exeption e) { }
    return value;
}

另外,如果您不想声明INTERVAL_NEVERString,请
替换

prefs.getString("interval", INTERVAL_NEVER));

prefs.getString("interval", "" + INTERVAL_NEVER));
于 2013-07-27T18:51:25.873 回答