Android 如何为包含GregoriaCalendar的对象创建可包裹代码
我不知道如何为包含Android 如何为包含GregoriaCalendar的对象创建可包裹代码,android,parcelable,parcel,Android,Parcelable,Parcel,我不知道如何为包含gregoriacalendar对象的对象创建正确实现Parcelable所需的代码 例如,对于包含字符串名称的对象用户和格列高利安达创作日期,我的尝试是: @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString
gregoriacalendar
对象的对象创建正确实现Parcelable
所需的代码
例如,对于包含字符串名称的对象用户
代码>和<代码>格列高利安达创作日期代码>,我的尝试是:
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeParcelable(this.creationDate, flags);
}
private User(Parcel in) {
this.name = in.readString();
this.creationDate = in.readParcelable(GregorianCalendar.class.getClassLoader());
}
public static final Creator<User> CREATOR = new Creator<User>() {
public User createFromParcel(Parcel source) {
return new User(source);
}
public User[] newArray(int size) {
return new User[size];
}
};
get writeParcelable无法应用于GregoriaCalendar错误
在
获取不兼容类型错误
如何正确编码包裹
编辑
我尝试了一些代码生成器,但使用了不同的方法,我不确定什么是正确的实现,第一个以这种方式使用writeValue和readValue:
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeValue(creationDate);
}
protected User(Parcel in) {
name = in.readString();
creationDate = (GregorianCalendar) in.readValue(GregorianCalendar.class.getClassLoader());
}
第二种用法
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeSerializable(creationDate);
}
protected User(Parcel in) {
name = in.readString();
creationDate = (GregorianCalendar) in.readSerializable();
}
什么是正确的方法?您可以使用第二种方法,因为GregoriaCalendar
实现了Serializable
,而Parcelable
将起作用
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeSerializable(creationDate);
}
protected User(Parcel in) {
name = in.readString();
creationDate = (GregorianCalendar) in.readSerializable();
}
但是您不能序列化GregorianCalendar,因为GregorianCalendar
相关类中的更新可能会导致问题。考虑加载一个包含<代码> GregorianCalendar < /Cord>的对象的情况,该文件用不同的API版本创建,差异<代码> GregorianCalendar < /代码>实现将导致肯定的错误,在SerialValueUnID Castor上有点不同,以防止文件的正确加载。
使用long
参数存储日期的毫秒,如果您不想重写整个应用程序,您可以轻松创建两种方法,根据需要从millis转换为GregoriaCalendar
,反之亦然。您尝试过使用吗?没有,但我尝试过使用可打包的代码生成器插件,但创建了错误的代码。您链接的站点在.readValue(GregorianCalendar.class.getClassLoader())中使用creationDate=(GregorianCalendar)代码>和dest.writeValue(creationDate)代码>您能确认这是打包GregoriaCalendar的正确方法吗?@Zhuinden请查看编辑。请参阅Calendar.getTimeInMillis/Calendar。setTimeInMillis@pskink什么意思?
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeSerializable(creationDate);
}
protected User(Parcel in) {
name = in.readString();
creationDate = (GregorianCalendar) in.readSerializable();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeSerializable(creationDate);
}
protected User(Parcel in) {
name = in.readString();
creationDate = (GregorianCalendar) in.readSerializable();
}