savedInstanceState.getParcelableArrayList() return

2019-08-08 14:37发布

问题:

If screen is rotated, I want to save list of My objects, so I implemented my Object as following:

public class Video implements Serializable, Parcelable {

private String mTitle;
private String mVideoID;
private String mThumbUrl;

public Video(String title, String id, String thumbUrl) {
this.mTitle = title;
this.mVideoID = id;
this.mThumbUrl = thumbUrl;
  }

 @Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub
    dest.writeString(mTitle);
    dest.writeString(mVideoID);
    dest.writeString(mThumbUrl);
}

public Video(Parcel in) {
    // TODO Auto-generated constructor stub
    mTitle = in.readString();
    mVideoID = in.readString();
    mThumbUrl = in.readString();
}

public static final Parcelable.Creator<Video> CREATOR = new Parcelable.Creator<Video>() {

    @Override
    public Video[] newArray(int size) {
        // TODO Auto-generated method stub
        return new Video[size];
    }

    @Override
    public Video createFromParcel(Parcel in) {
        // TODO Auto-generated method stub
        Log.e("CREATOR", in.readString());
        return new Video(in);
    }
};

}

And in the MainActivity, i retrieved saved list of objects:

  if (savedInstanceState != null) {
        ArrayList<Video> saved = savedInstanceState.getParcelableArrayList(VIDEO_LIST);

        Toast.makeText(this, "Count: " + saved.size(), Toast.LENGTH_SHORT)
                .show();
    }

--> The problem is, After rotating screen list of objects is empty: saved.size() = 0 Please tell me why? I how can i resolve it. Thanks

回答1:

this variable savedInstanceState is inside onCreate method right??

for that variable be different than null, you need to save the object inside the method onSaveInstanceState (Bundle outState), like this:

protected void onSaveInstanceState (Bundle outState){
    outState.putParcelable(VIDEO_LIST, videoList);
}

more info here.

-----------Update-----------

the android document say that onSaveInstanceState is only called when the app is killed.

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state.

Since you are only rotating the screen, the app is not killed, your activity is only recreate. That is why the variable is null.