SharedPreferences仅返回默认值 [英] SharedPreferences return only default value
本文介绍了SharedPreferences仅返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,不是创建数据库,而是使用SharedPreference
存储数据.
So instead of creating a database, I'm storing the data using SharedPreference
.
我的代码如下:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putInt("favid"+id, 1);
editor.commit();
Toast.makeText(getApplicationContext(), "Select as favorite", Toast.LENGTH_SHORT).show();
现在,我想检索该数据,因此在其他活动中使用了以下代码:
Now I want to retrieve that data so I have used below code in other activity:
strFav = new ArrayList<Integer>();
if(strFav.size()>0)
strFav.clear();
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
for (int i = 1; i < 19; i++) {
int favid = prefs.getInt("favid"+i, -1);
if (favid != -1)
{
strFav.add(i);
}
}
在检索数据时,我得到的所有值都是-1
.
At time of data retrieve, I'm getting all value is -1
.
有人能帮助我为什么会这样吗?我已经提交了很多条目,但都为1,但是我仍然得到所有条目的-1
结果.
Can any body help me why this is happening? I have committed many entries as 1, but I'm still getting -1
result for all of them.
推荐答案
请参见文档关于getPrefernces
方法:
检索SharedPreferences对象以访问此活动专用的首选项.
So, if you want to share preferences between activities you should use getSharedPreferences
with specified name.
这篇关于SharedPreferences仅返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文