在Sharedpreferences中将stored int转换为long

时间:2014-12-11 07:50:24

标签: android sharedpreferences

我有一个正在制作的应用程序,可以在共享优势中存储大量数据。

某些数据存储为int,使用sp.setInt ...

实现

我遇到的问题是,存储为int的一些数字很大并且被泄露给了一些数字。

如何安全地转换为将数据存储为int的现有用户,以保持长时间?而不是setInt,我想要setLong和getLong。

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

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

您无法使用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共享偏好是否存在以及是否存在使用int读取旧SharedPreferences#getInt值,并使用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();
}

答案 1 :(得分:0)

你应该使用单独的变量来存储多长时间。

如果要复制现有用户的数据,

您可以执行以下检查,

spEditor.putLong("myLong" , (long) sp.getInt("myInt", 0)); 

并保存。以上是示例代码。不是完整的代码。

答案 2 :(得分:0)

将类型设置为共享首选项字段后,几乎无法更改它。您最好的调用是创建一个新字段,然后在应用程序内部提供一个包装器方法,它将所有对前一个(int)字段的调用重定向到新的(长)字段。

答案 3 :(得分:0)

要通过@ michal.z添加the answer,您可以捕获ClassCastException并重试获取Integer。

所以你得到:

long l=0;
try {
    l = sharedPrefs.getLong("myint", 1L);
} catch (ClassCastException) {
    l = sharedPrefs.getInt("myint", 1L);
    if (l<0) {
        l += 0x80000000L;
    }
}

还有一个好消息:一旦你保存了&#34; myint&#34;作为一个长期,例外将不再发生。