How to save an instance of a custom class in onSaveInstanceState?

前端 未结 5 2045
臣服心动
臣服心动 2020-12-02 12:33

I created an instance of a custom class RestaurantList to hold my data (a list of restaurant data received from a web service as json data).

How can I save it in

5条回答
  •  孤城傲影
    2020-12-02 12:52

    Custom objects can be saved inside a Bundle when they implement the interface Parcelable. Then they can be saved via:

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putParcelable("key", myObject);
        }
    

    Basically the following methods must be implemented in the class file:

     public class MyParcelable implements Parcelable {
         private int mData;
    
         public int describeContents() {
             return 0;
         }
    
         /** save object in parcel */
         public void writeToParcel(Parcel out, int flags) {
             out.writeInt(mData);
         }
    
         public static final Parcelable.Creator CREATOR
                 = new Parcelable.Creator() {
             public MyParcelable createFromParcel(Parcel in) {
                 return new MyParcelable(in);
             }
    
             public MyParcelable[] newArray(int size) {
                 return new MyParcelable[size];
             }
         };
    
         /** recreate object from parcel */
         private MyParcelable(Parcel in) {
             mData = in.readInt();
         }
     }
    

提交回复
热议问题