savedInstanceState.getParcelableArrayList()返回空列表列表、savedInstanceState、getParcelableArrayList

2023-09-12 22:26:52 作者:[藏在我心里的人]

如果屏幕旋转时,我要救我的对象列表,让我实现了我的目标如下:

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

公共类视频实现Serializable,Parcelable {

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);
    }
};

}

而在MainActivity,取出了我救对象列表:

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();
    }

- >问题是,旋转物体的画面列表之后是​​空的:saved.size()= 0 请告诉我为什么?我如何解决它。谢谢

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

推荐答案

这个变量savedInstanceState里面onCreate方法正确?

this variable savedInstanceState is inside onCreate method right??

该变量大于零的不同,你需要保存对象的方法的onSaveInstanceState(包outState)里面,像这样的:

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);
}

更多信息这里

----------- -----------更新

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

Android的文件说的onSaveInstanceState是,当应用程序被杀害只调用。

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.