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.
See docs about
getPrefernces
method:So, if you want to share preferences between activities you should use
getSharedPreferences
with specified name.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
what's about id is equals to 0? here you are reading starting from 1