I have a ListActivity containing Items which are fetched from a JSON Object. When the user click one of the item, each item displays its details and attributes inside a DetailActivity class.
So I have one Activity to display the selected Item's attributes from the ListActivity. On the DetailActivity class there is a CheckBox, to mark the the Item as 'Favorite'. So every time the CheckBox inside the DetailActivity is checked, when the user opens the DetailActivity of that Item again, the state of the CheckBox is always checked.
I implemented so far by putting Boolean through SharedPreferences. But my method only saves the state of the DetailActivity class regardless which Item isChecked as favorite. So it doesn't save the state of a certain item, only the state of DetailActivity class.
How am I am able to do so?
Here is my snippet:
final CheckBox cb_fav = (CheckBox) findViewById(R.id.cb_tool_fav);
cb_fav.setOnClickListener(this);
boolean isChecked = getBooleanFromPreferences("isChecked");
Log.i("start",""+isChecked);
cb_fav.setChecked(isChecked);
cb_fav.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.i("boolean",""+isChecked);
DetailsActivity.this.putBooleanInPreferences(isChecked,"isChecked");
}
});
}
public void putBooleanInPreferences(boolean isChecked,String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.commit();
}
public boolean getBooleanFromPreferences(String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
}
Here's the object class I'm fetching to my ListActivity, these are the attributes which are displayed inside the DetailsActivity class.
public class VideoLocation {
public String deleted_at = null;
public int documentary_video_length = -1;
public int id = -1;
public double latitude = 0d;
public double longitude = 0d;
public int position = -1;
public String updated_at = null;
public String name = null;
public String text = null;
public String documentary_video_url = null;
public String documentary_thumbnail_url = null;
public String audio_text_url = null;
public Footage[] footages = null;
public VideoLocation(){
}