当我运行应用程序并浏览不同的 fragment 时,我的类看起来像这样,有时它会崩溃,logcat 说错误是 BadParcelableException:Parcelable 协议(protocol)需要在类 ge.mobility.weather.entity 上有一个名为 CREATOR 的 Parcelable.Creator 对象。城市
这是我的代码
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class City implements Parcelable {
private String code;
private String name;
private List<CityWeather> weathers ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<CityWeather> getWeathers() {
if(weathers == null) {
weathers = new ArrayList<CityWeather>();
}
return weathers;
}
public void addCityWeather(CityWeather w) {
getWeathers().add(w);
}
public void addCityWeathers(List<CityWeather> w) {
getWeathers().addAll(w);
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {enter code here
// TODO Auto-generated method stub`enter code here`
}
}
最佳答案
您需要实现 Parcelable.Creator 并添加 un/serialise 方法和构造函数:
public City(Parcel in) {
readFromParcel(in);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(code);
dest.writeString(name);
dest.writeTypedList(weathers);
}
private void readFromParcel(Parcel in) {
code = in.readString();
name = in.readString();
in.readTypedList(weathers, CityWeather.CREATOR);
}
public static final Parcelable.Creator<City> CREATOR = new Parcelable.Creator<City>() {
public City createFromParcel(Parcel in) {
return new City(in);
}
public City[] newArray(int size) {
return new City[size];
}
};
您还需要为 CityWeather
类实现 Parcelable 方法。
关于java - 创建可分割类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21802080/