简体   繁体   English

在现有的SharedPreference值内更改数据类型

[英]Changing Datatype within an already existing SharedPreference Value

I am in the process of cleaning up some bad coding choices in some really old apps. 我正在清理一些非常老的应用程序中的一些错误的编码选择。 In one of the first apps I did, it has a user login. 在我做过的第一批应用程序中,有一个用户登录名。 So, I use SharedPreferences to store the user_id . 因此,我使用SharedPreferences来存储user_id This should have been a long all along. 这应该一直很long Unfortunately, I originally stored it as a String . 不幸的是,我最初将其存储为String

I am going back and correcting this. 我要回过头来纠正此问题。 However, I of course get a ClassCastException since I am trying to pull out a String as a long . 但是,我当然会收到ClassCastException因为我试图将String提取为long

This is my code on how it works AFTER changing it: 这是我的代码,关于更改后的工作方式:

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);
}

What is the cleanest way to handle this so it is as transparent as possible to the user (I don't want to force a log out if possible). 什么是最干净的处理方式,以便对用户尽可能地透明(如果可能,我不想强​​制注销)。

EDIT 编辑

As I am typing this, is aa good solution? 当我输入此内容时,这是一个好的解决方案吗?

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

A problem : This would only work the first time to workaround old data; 问题 :这只会在第一次解决旧数据时起作用; because after that, the preference would be a long based on the setter method. 因为在那之后,基于setter方法的偏好会很long

Next best option: Can I test the type stored in the preference , maybe with a typeof ? 下一个最佳选择:是否可以使用typeof测试存储在preference的类型?

put this in your MainActivity before this value is called for the first time 在第一次调用此值之前,将其放入您的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();
        }

and at your next update you can remove it. 并在您下次更新时将其删除。

  1. In getLoggedInUserId , catch the class cast exception getLoggedInUserId ,捕获类getLoggedInUserId异常

  2. Read the (String) value of the shared preference and convert it with Long.parseLong() 读取共享首选项的(字符串)值,并使用Long.parseLong()转换

  3. Create an editor, put the long value, and commit. 创建一个编辑器, put长期价值,并提交。

This code will run exactly once and then you will no longer have to worry about edge cases. 此代码将只运行一次,因此您不必再担心边缘情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM