Saving state of ArrayList of custom objects
I have a member variable in my Activity which is an ArrayLis开发者_C百科t. The objects populating this ArrayList are objects I have defined called RatingItem. RatingItem has several member vars like rating, comment, id, etc.
I would like to save this ArrayList in onSaveInstanceState so it can be repopulated from onRestoreInstanceState. What is the best way to do this? I've never saved the state of an object of this complexity.
Thank you for your help
You should probably have your object implement Parcelable. Basically, you have to add methods to write and read the members of your object from a Parcel
, and then add custom CREATOR
inner class that has a couple of static factory methods. There's a demo of it on the first linked page, but it's not too hard.
Then you can just save the whole list in one go with Bundle.putParcelableArrayList()
. (You'll have to cast the list when you get it back out with Bundle.getParcelableArrayList()
but it will work fine.)
One option is to iterate over your ArrayList in onSaveInstanceState and do something like
RatingItem ri = list.get(i);
ri.saveState(bundle);
The custom saveState
call can then go about saving its individual state to the bundle, like so:
static final String RATING_KEY = "RATING_KEY";
int myId;
int myRating;
void saveState(bundle)
{
bundle.putInt(RATING_KEY + "_" + myId, myRating);
}
The myId
member field should be set in RatingItem's constructor, and is used to ensure that all the member fields in an item can be linked back to a particular item at restore time (by reversing the above and using bundle.getInt()
with appropriate key+id).
精彩评论