Saving state of ArrayList of custom objects

前端 未结 2 556
清歌不尽
清歌不尽 2020-12-18 16:33

I have a member variable in my Activity which is an ArrayList. The objects populating this ArrayList are objects I have defined called RatingItem. RatingItem has several m

相关标签:
2条回答
  • 2020-12-18 16:46

    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).

    0 讨论(0)
  • 2020-12-18 16:51

    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.)

    0 讨论(0)
提交回复
热议问题