SharedPreferences return only default value

安稳与你 提交于 2019-12-31 01:33:59

问题


So instead of creating a database, I'm storing the data using SharedPreference.

My code is below:

   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);
        }
    }

At time of data retrieve, I'm getting all value is -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.


回答1:


See docs about getPrefernces method:

Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

So, if you want to share preferences between activities you should use getSharedPreferences with specified name.




回答2:


Do you use shared preferences in two different activieties of one app ?

Also try to specify preferences name, or use some Manager to handle all preferences, all this explained here




回答3:


editor.putInt("favid"+id, 1);

what's about id is equals to 0? here you are reading starting from 1

 for (int i = 1; i < 19; i++) {


来源:https://stackoverflow.com/questions/13841488/sharedpreferences-return-only-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!