【发布时间】: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