因此,我试图将一个对象从一个活动发送到另一个活动,但接收器端上的对象始终为null。该对象完全填充在发件人侧,因此我几乎可以肯定它必须对阅读对象做一些事情。
这是包裹的对象:
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");
}
编辑:我已经检查了有关包裹的所有其他主题,我也遵循了本教程,我找不到错误的区别。
编辑2 :问题已解决。从一开始,一切都很好,但是由于某种原因,我在用数据和putextra填充对象之间放了更多代码,所以基本上我是在发送一个空的对象 _(ツ)_/¯
首先避免通过位图,它们可能太大,并将字符串"first"
提取到ReceiverActivity
类的常数:
public class ReceiverActivity extends ... {
public static final String EXTRA_FIRST = "first";
...
}
so:
i.putExtra(ReceiverActivity.EXTRA_FIRST,firstPic);
和
currentPicture = intent.getParcelableExtra(ReceiverActivity.EXTRA_FIRST);
我已经发生了这种奇怪的事情,我以这种方式解决了它。