我有一个实现Parcelable的类。该类有1个int和2个String。 读取时只返回int数据。第一个字符串返回为“”,第二个字符串返回为null。
写包裹 -
After writing int - data position 376 parcel size 376.
After writing String1 - data position 392 parcel size 392.
After writing String2 - data position 412 parcel size 412.
阅读包裹 -
After reading int - data position 112 parcel size 152.
After reading String1 - data position 120 parcel size 152.
After reading String2 - data position 124 parcel size 152.
读取宗地数据时数据大小是否相同?
实现Parcelable的类 -
public class Message implements Parcelable {
private long id;
private String from;
private String message;
private String TAG = Message.class.getSimpleName();
public static final Parcelable.Creator<Message> CREATOR = new Parcelable.Creator<Message>() {
@Override
public Message createFromParcel(Parcel source) {
return new Message(source);
}
@Override
public Message[] newArray(int size) {
Log.v("Message", "New array size " + size);
return new Message[size];
}
};
public Message(){
}
private Message(Parcel source){
id = source.readInt();
Log.v(TAG, "Reading parcel object data position " + source.dataPosition() + " parcel size " + source.dataSize());
from = source.readString();
Log.v(TAG, "Reading parcel object data position " + source.dataPosition() + " parcel size " + source.dataSize());
message = source.readString();
Log.v(TAG, "Reading parcel object data position " + source.dataPosition() + " parcel size " + source.dataSize());
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the from
*/
public String getFrom() {
return from;
}
/**
* @param from the from to set
*/
public void setFrom(String from) {
this.from = from;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Message [id=" + id + ", from=" + from + ", message=" + message
+ "]";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
Log.v(TAG, "Writing parcel object " + flags + " -- " + id + " -- " + from + " -- " + message);
dest.writeLong(id);
Log.v(TAG, "Writing parcel object data position " + dest.dataPosition() + " parcel size " + dest.dataSize());
/*dest.writeString(from);
dest.writeString(message);*/
dest.writeString("from");
Log.v(TAG, "Writing parcel object data position " + dest.dataPosition() + " parcel size " + dest.dataSize());
dest.writeString("message");
Log.v(TAG, "Writing parcel object data position " + dest.dataPosition() + " parcel size " + dest.dataSize());
}
}
答案 0 :(得分:3)
问题是,我正在使用writeLong()但是在读取时正在执行readInt()。 用readLong()替换了readInt(),现在它工作正常。