为什么不能将INT保存到SharedPreferences? [英] Why cannot save INT to SharedPreferences?

查看:81
本文介绍了为什么不能将INT保存到SharedPreferences?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题.我从来没有过.当我尝试将int值保存到我的SharedPreference中,然后在其他Activity中恢复时.即使我在那里保存其他值,该值也始终为0(例如:1);

I have a strange problem. I have never had it before. When I try to save int value to my SharedPreference and then restore in other Activity. Value is always 0 even if I save there other value (for example: 1);

private String Number;
private String Profile;

,然后将值(在这种情况下为"1")保存到第一个活动中的SharedPreferences中:

and then saving values (in this case "1") to SharedPreferences in first Activity:

SharedPreferences a = FirstActivity.this.getSharedPreferences("a", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorProfiles = a.edit();
prefsEditorProfiles.putInt(Profile, 1);
prefsEditorProfiles.putInt(Number, 1);
prefsEditorProfiles.commit();

然后在其他活动中恢复SharedPreferences:

then restore SharedPreferences in other Activity:

SharedPreferences a = SecondActivity.this.getSharedPreferences("a", MODE_PRIVATE);
int ab = a.getInt(Number, 0);

应用程序显示0而不是1.我的其他SharedPreferences效果很好.我不知道问题出在哪里.

And application shows me 0 instead of 1. My other SharedPreferences works great. I don't know where is the problem.

推荐答案

我要检查您声明的Number和Profile变量的值是什么...您将它们的值用作键,因此,如果它们的名称冲突,即使代码看起来正确,您也可能会覆盖另一设置.

I'd check what's the value of the Number and Profile variables you declared... you are using their values as keys, so if they have conflicting names, you might be overwriting one setting with the other even though the code looks right.

我建议将其替换:

私有字符串号;
私有字符串配置文件;

private String Number;
private String Profile;

与此:

私有最终字符串NUMBER ="Number";
私有最终字符串PROFILE ="Profile";

private final String NUMBER = "Number";
private final String PROFILE = "Profile";

然后在设置/获取您的首选项值时使用这些常量.

And then using those constants when setting/getting your preference value.

这篇关于为什么不能将INT保存到SharedPreferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆