savedInstanceState尚未恢复

时间:2015-09-15 16:56:12

标签: android android-lifecycle

我刚刚开始使用Android,我遇到了以下问题:

我在打开新Activity时尝试saveInstanceState,当Activity恢复为Visible状态时我需要恢复该状态。

这是我的onSaveInstanceState方法

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList("movies", (ArrayList<Movie>) movies);

    Log.v("onSaveInstanceState ", "SAVING STATE");
    Log.v("Saving State", outState.toString());
}

这是我的onCreate方法,应该恢复以前保存的实例状态

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null){
        Log.v("onCreate ", "EXISTING STATE");
        this.movies = savedInstanceState.getParcelableArrayList("movies");
    }else{
        Log.v("onCreate ", "EMPTY STATE");
    }

    setHasOptionsMenu(true);
}

如果您注意到,在onSaveInstanceState方法中,在保存实例后,我在保存的实例上执行toString(),它会显示包含我保存的值的完整实例。但是,当我恢复实例时,savedInstanceState变量将为null。

我正在使用一个自定义对象Array,其中每个对象都实现了Parcelable。

以下是课程:

public class Movie implements Parcelable {
private String title;
private String path;
private String overview;
private String releaseDate;
private double vote;

public Movie(String title, String overview, double vote, String releaseDate, String path) {
    this.title = title;
    this.overview = overview;
    this.vote = vote;
    this.releaseDate = releaseDate;
    this.path = path;
}

public String getTitle() {
    return title;
}

public String getPath() {
    return path;
}

public String getOverview() {
    return overview;
}

public String getReleaseDate() {
    return releaseDate;
}

public double getVote() {
    return vote;
}

protected Movie(Parcel source){
    this.title = source.readString();
    this.path = source.readString();
    this.overview = source.readString();
    this.releaseDate = source.readString();
    this.vote = source.readDouble();

}

public static final Creator<Movie> CREATOR = new Creator<Movie>() {
    @Override
    public Movie createFromParcel(Parcel source) {
        return new Movie(source);
    }

    @Override
    public Movie[] newArray(int size) {
        return new Movie[size];
    }
};

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(title);
    dest.writeSerializable(path);
    dest.writeString(overview);
    dest.writeString(releaseDate);
    dest.writeDouble(vote);
}

@Override
public String toString() {
    return "Movie{" +
            "title='" + title + '\'' +
            ", path='" + path + '\'' +
            ", overview='" + overview + '\'' +
            ", releaseDate='" + releaseDate + '\'' +
            ", vote=" + vote +
            '}';
}

}

我觉得我以某种方式以错误的方式保存它。我按照教程了解了如何做到这一点。请让我知道我做错了什么。谢谢

enter image description here

1 个答案:

答案 0 :(得分:1)

通过在清单文件中添加MainActivity来解决我的问题。

android:launchMode="singleTop"

创建了多个Activity实例,因此不会保存实例。