如下代码:
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();