gpt4 book ai didi

android - 无法转换为 java.lang.Long Android SharedPreferences

转载 作者:行者123 更新时间:2023-11-29 19:04:50 25 4
gpt4 key购买 nike

全新安装我的应用程序后出现以下异常:

java.lang.RuntimeException: Unable to start activity ... 
java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.Long

( Activity )代码:

长时间初始化(在 onCreate 之外):

long spinTimer = 0L;

从 pefs 分配先前的 long val 或默认为 0L(在 onCreate 内):

spinTimer = settings.getLong("spinTimer", 0L);

应该是long,int从哪里来?

Sharepref 获取其值的其他代码引用(全部长):

if (item.equals("Select...")) {editor.putLong("spinTimer", 0L);}
if (item.equals("5 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (5 * 60 * 1000));}
if (item.equals("10 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (10 * 60 * 1000));}
if (item.equals("15 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (15 * 60 * 1000));}
if (item.equals("30 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (30 * 60 * 1000));}
if (item.equals("1 hour")) {editor.putLong("spinTimer", System.currentTimeMillis() + (60 * 60 * 1000));}
editor.commit();
spinTimer = settings.getLong("spinTimer", 0L);

清除APP数据后,一切正常。我不应该每次重新安装应用程序时都这样做。

int 到底是怎么潜入那里的?

Requested DEBUG INFO - 不标准,但认为这应该足够了:

发生崩溃的相关代码行(简单 Activity ):

log.debug("***Activity Start***");
log.debug("OnCreateEnter");
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
log.debug("spinTimer: {}", spinTimer);
spinTimer = settings.getLong("spinTimer", 0L); // <-- APP crashes right here

输出:

***Activity Start***
OnCreateEnter
spinTimer: 0

1) 如果没有赋值,.getLong (0L) 的第二个参数是否应该赋值给变量 (spinTimer)?我也试过“0”。

2) int 是如何赋值的?键 'spinTimer' (0L) 和 var 'spinTimer' ('long spinTimer = 0L;') 都被初始化为 longs。

3) 如果我清除应用程序数据(全新安装后)- 一切正常;

4) 如果我在上述语句之前添加以下代码行 - 一切顺利(但这种方法扭曲了我的逻辑):

editor.putLong("spinTimer", spinTimer);
editor.commit();

最佳答案

java.lang.ClassCastException: java.lang.Integer cannot be cast to 
java.lang.Long

由于ClassCastException问题,你应该使用Long.valueOf .

Returns a Long instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructor Long(long), as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values within a particular range.

editor.putLong("spinTimer", Long.valueOf(System.currentTimeMillis() + (5 * 60 * 1000))

关于android - 无法转换为 java.lang.Long Android SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47688454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com