android:SharedPreference 读取失败的原因及解决办法

如下代码:
private int typeLastItem = 0;
private int areaLastItem = 0;
private int timeLastItem = 0;

读取数据:
SharedPreferences sp = getSharedPreferences("yst_filter", Context.MODE_PRIVATE);
typeLastItem = sp.getInt("yst_filter_type", -1);
areaLastItem = sp.getInt("yst_filter_area", -1);
timeLastItem = sp.getInt("yst_filter_time", -1);

写入数据:
SharedPreferences sp = getSharedPreferences("yst_filter", Context.MODE_PRIVATE);
sp.edit().putInt("yst_filter_type", 1);
sp.edit().putInt("yst_filter_area", 2);
sp.edit().putInt("yst_filter_time", 3);
sp.edit().commit();

以上代码,不管怎么读取,三个值均为默认值-1,打印log,显示 sp.edit().commit()结果为true,但就是读取值为默认值-1。

原因:
就出在下面这几句代码这里
sp.edit().putInt("yst_filter_type", 1);
sp.edit().putInt("yst_filter_area", 2);
sp.edit().putInt("yst_filter_time", 3);
sp.edit().commit();
四句代码相当于四个Editor mEditor = sp.edit();前面三个只是putInt,并没有commit,第四个有commit,但没有put,所以读取的值均为默认值。
结论:上面四句写法是错误的。

解决办法:
将上面四句改为以下两种方法中的任何一种均可:
第一种:
Editor edit = sp.edit();
edit.putInt("yst_filter_type", typeLastItem);
edit.putInt("yst_filter_area", areaLastItem);
edit.putInt("yst_filter_time", timeLastItem);
edit.commit();

第二种:
sp.edit().putInt("yst_filter_type", typeLastItem)
.putInt("yst_filter_area", areaLastItem)
.putInt("yst_filter_time", timeLastItem).commit();

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值