任何人都可以告诉我这段代码有什么问题吗?
Parcelable class
package com.airwatch.agent.finddevice;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Represents the configuration supplied from device services
* regarding the find device command.
*/
public class FindDeviceConfig implements Parcelable{
public FindDeviceConfig() {
}
/**
* number of loops to play ring-tone.
*/
private String numberoftime;
/**
* Delay between loops - in seconds.
*/
private String interval;
public FindDeviceConfig(String numberoftime, String interval) {
this.numberoftime = numberoftime;
this.interval = interval;
}
public String getNumberoftime() {
return numberoftime;
}
public void setNumberoftime(String numberoftime) {
this.numberoftime = numberoftime;
}
public String getInterval() {
return interval;
}
public void setInterval(String interval) {
this.interval = interval;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
//dest.writeInt(Integer.parseInt(numberoftime));
//dest.writeInt(Integer.parseInt(interval));
dest.writeString(this.interval);
dest.writeString(this.numberoftime);
}
public static final Parcelable.Creator<FindDeviceConfig> CREATOR = new Parcelable.Creator<FindDeviceConfig>() {
public FindDeviceConfig createFromParcel(Parcel in) {
return new FindDeviceConfig(in);
}
public FindDeviceConfig[] newArray(int size) {
return new FindDeviceConfig[size];
}
};
public FindDeviceConfig(Parcel parcel)
{
parcel.setDataPosition(0);
interval=parcel.readString();
numberoftime=parcel.readString();
}
}
放置可分割的对象。
FindDeviceConfig config=new FindDeviceConfig("3","2");
intent.putExtra("finddevice_config", config);
读取parcelable对象。
FindDeviceConfig config = intent.getParcelableExtra("finddevice_config");
有人遇到过这个问题吗?
答案 0 :(得分:1)
添加以下构造函数:
public FindDeviceConfig(Parcel data) {
this.numberoftime = data.readString();
this.interval = data.readString();
}
答案 1 :(得分:0)
我遇到了同样的问题,但是有一个不同的解决方案,所以请在此处发布以备将来参考。
使用Parcelable
时要记住的最重要的事情是,将变量写入Parcel的顺序也应该是您阅读它的顺序。
例如,
//wirting to Parcel
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.interval); //interval first
dest.writeString(this.numberoftime); //numberoftime second
}
//reading from Parcel
public FindDeviceConfig(Parcel parcel)
{
Wrong order -- this will not work or give unwanted result
numberoftime=parcel.readString();
interval=parcel.readString();
}
//Correct Order
public FindDeviceConfig(Parcel parcel)
{
interval=parcel.readString(); //interval first
numberoftime=parcel.readString(); //numberoftime second
}
快乐编码:)