2014-02-15 62 views
0

我的类看起来像这样当我运行我的应用程序并导航通过不同的片段有时它崩溃和logcat说错误是BadParcelableException:Parcelable协议需要一个Parcelable.Creator对象调用类ge.mobility.weather上的CREATOR .entity.City创建parcelable类

这里是我的代码

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` 

    } 
} 

回答

1

您需要实现Parcelable.Creator并添加联合国/序列化的方法和构造:

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方法。