4

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.

JorgeAmVF
  • 1,660
  • 3
  • 21
  • 32
Siddhpura Amit
  • 14,534
  • 16
  • 91
  • 150

3 Answers3

6

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.

Jin35
  • 8,602
  • 3
  • 32
  • 52
1

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

Community
  • 1
  • 1
dilix
  • 3,761
  • 3
  • 31
  • 55
0
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++) {
Blackbelt
  • 156,034
  • 29
  • 297
  • 305