gpt4 book ai didi

android - savedInstanceState 没有被恢复

转载 作者:行者123 更新时间:2023-11-29 01:28:27 24 4
gpt4 key购买 nike

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

我正在尝试在打开新 Activity 时保存 InstanceState,并且我需要在 Activity 返回可见状态时恢复该状态。

这是我的 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。

我正在使用一个自定义对象数组,其中每个对象都实现了 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

最佳答案

我的问题通过添加到 list 文件中的 MainActivity 得到解决。

android:launchMode="singleTop"

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

关于android - savedInstanceState 没有被恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32591613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com