所以我试图将一个对象从一个活动发送到另一个活动作为Parcelable,但接收方的对象始终为null。对象完全填充在发送方,所以我几乎可以肯定它必须做一些阅读对象的事情。
以下是Parcelable对象:
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
public class Picture implements Parcelable {
public String pictureID, title, year, price, author;
public Bitmap picture;
public Picture(){
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(pictureID);
dest.writeString(title);
dest.writeString(year);
dest.writeString(price);
dest.writeString(author);
dest.writeParcelable(picture, flags);
}
protected Picture(Parcel in) {
pictureID = in.readString();
title = in.readString();
year = in.readString();
price = in.readString();
author = in.readString();
picture = in.readParcelable(Bitmap.class.getClassLoader());
}
public static final Parcelable.Creator<Picture> CREATOR = new Parcelable.Creator<Picture>() {
public Picture createFromParcel(Parcel source) {
return new Picture(source);
}
public Picture[] newArray(int size) {
return new Picture[size];
}
};
}
发件人活动:
Picture firstPic = new Picture();
firstPic.pictureID = "1";
firstPic.title = "Mona Lisa";
firstPic.author = "Leonardo Da Vinci";
firstPic.price = "99999000";
firstPic.year = "2250";
firstPic.picture = BitmapFactory.decodeResource(getApplication().getResources(),R.drawable.monalisa);
Intent i = new Intent(getApplicationContext(),MainScreen.class);
i.putExtra("first",firstPic);
startActivity(i);
finish();
接收者活动:
Picture currentPicture = new Picture();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
currentPicture = intent.getParcelableExtra("first");
}
编辑:我已经检查了有关Parcelable的所有其他主题,我也跟着this tutorial,我无法找到错误可能出现的差异。
编辑2 :问题已解决。从一开始一切都工作正常但由于某种原因我在填充对象与数据和putExtra之间放了一些代码所以基本上我发送一个空对象¯\ _ _(ツ)_ /¯
答案 0 :(得分:0)
首先避免传递Bitmap,它们可能太大并且将字符串"first"
提取到ReceiverActivity
类的常量:
public class ReceiverActivity extends ... {
public static final String EXTRA_FIRST = "first";
...
}
所以:
i.putExtra(ReceiverActivity.EXTRA_FIRST,firstPic);
并且
currentPicture = intent.getParcelableExtra(ReceiverActivity.EXTRA_FIRST);
这个奇怪的事情已经发生在我身上,我用这种方式解决了它。