【问题标题】:Changing Datatype within an already existing SharedPreference Value在现有的 SharedPreference 值中更改数据类型
【发布时间】:2016-03-08 18:02:09
【问题描述】:

我正在清理一些非常旧的应用程序中的一些错误编码选择。在我做的第一个应用程序之一中,它有一个用户登录。所以,我使用SharedPreferences 来存储user_id。这应该一直是long。不幸的是,我最初将其存储为String

我要回去纠正这个问题。但是,我当然会得到一个ClassCastException,因为我试图将String 提取为long

这是我更改后如何工作的代码:

public static void setLoggedInUserId(Context ctx, long id) {
    Editor editor = getSharedPreferences(ctx).edit();
    editor.putLong(PREF_LOGGEDIN_USER_USERID, id);
    editor.apply();
}

public static long getLoggedInUserId(Context ctx) {
    // need to handle String to long conversion here?
    return getSharedPreferences(ctx).getLong(PREF_LOGGEDIN_USER_USERID, 0);
}

处理此问题的最简洁方法是什么,以便对用户尽可能透明(如果可能,我不想强​​制注销)。

编辑

当我输入这个时,这是一个好的解决方案吗?

return Long.valueOf(getSharedPreferences(ctx).getString(PREF_LOGGEDIN_USER_USERID, 0));

一个问题:这只能在第一次解决旧数据时起作用;因为在那之后,首选项将是基于 setter 方法的long

下一个最佳选择:我可以测试存储在preference 中的类型吗,也许使用typeof

【问题讨论】:

    标签: java android string sharedpreferences classcastexception


    【解决方案1】:
    1. getLoggedInUserId中,捕获类转换异常

    2. 读取共享首选项的(字符串)值并将其转换为Long.parseLong()

    3. 创建一个编辑器,put long 值,然后提交。

    此代码将只运行一次,然后您将不再需要担心边缘情况。

    【讨论】:

      【解决方案2】:

      在第一次调用这个值之前把它放在你的 MainActivity 中

              if(!prefs.getBoolean("ConversionDone", false)){
                  String currentStringValue = prefs.String(PREF_LOGGEDIN_USER_USERID, 0);
                  prefs.edit().remove(PREF_LOGGEDIN_USER_USERID).commit();
                  prefs.edit().putLong(PREF_LOGGEDIN_USER_USERID, Long.parseLong(currentStringValue)).commit();
                  prefs.edit().putBoolean("ConversionDone", true).commit();
              }
      

      您可以在下次更新时将其删除。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-07
        • 1970-01-01
        • 1970-01-01
        • 2019-05-28
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        • 2019-07-14
        相关资源
        最近更新 更多