gpt4 book ai didi

android - 在 Sharedpreferences 中将 stored int 转换为 long

转载 作者:行者123 更新时间:2023-11-29 17:44:48 27 4
gpt4 key购买 nike

我有一个正在生产的应用程序,它在 sharedprefrences 中存储大量数据。

一些数据存储为使用 sp.setInt 实现的 int...

我有一个问题,一些存储为 int 的数字太大并且被泄露为负数。

我如何安全地对现有用户进行转换,使数据存储为 int,以保持 long?那不是 setInt,我想要 setLong 和 getLong。

我必须确保当我对当前存储的 int 执行 getLong 时它不会崩溃。

感谢您的帮助!

最佳答案

您不能使用 SharedPreferences#getLong 获取以前存储为 int 的共享首选项。

int i = 2;
Editor editor = sharedPrefs.edit();
editor.putInt("myint", i);
editor.apply();
long l = sharedPrefs.getLong("myint", 1L);

以上代码抛出 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long。因此,应使用新的单独共享首选项将您的值存储为 long。如果您想将数据从 int 共享偏好移动到 long 现有用户的共享偏好,请执行 Ganapathy 指出的操作。检查 int 共享首选项是否存在,如果存在,则使用 SharedPreferences#getInt 读取旧的 int 值并将其存储在新的 long 使用 SharedPreferences#putLong 共享首选项。那么您可能还应该删除旧的 int 共享首选项。

if(sharedPrefs.contains("myint")) {
Editor edit = sharedPrefs.edit();
edit.putLong("mylong" , (long) sharedPrefs.getInt("myInt", 0));
edit.apply();
edit.remove("myint");
edit.apply();
}

关于android - 在 Sharedpreferences 中将 stored int 转换为 long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27417776/

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