如何保存的onSaveInstanceState自定义类的实例? [英] How to save an instance of a custom class in onSaveInstanceState?

查看:663
本文介绍了如何保存的onSaveInstanceState自定义类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义类RestaurantList一个实例来保存我的数据(从Web服务接收到的JSON数据餐厅数据的列表)。

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

我怎样才能将其保存在的onSaveInstanceState

How can I save it in onSaveInstanceState?

推荐答案

自定义对象可以保存里面包时,他们实现的接口 Parcelable 。 然后,他们可以通过保存:

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<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         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();
     }
 }

这篇关于如何保存的onSaveInstanceState自定义类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆