SharedPreferences return only default value

2019-02-25 11:22发布

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.

3条回答
混吃等死
2楼-- · 2019-02-25 11:43

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.

查看更多
混吃等死
3楼-- · 2019-02-25 11:45

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

查看更多
ゆ 、 Hurt°
4楼-- · 2019-02-25 11:48
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++) {
查看更多
登录 后发表回答