0

所以我试图将一个对象作为 Parcelable 从一个活动发送到另一个活动,但接收方的对象始终为空。该对象在发送方已完全填充,因此我几乎可以肯定它必须通过读取该对象来做一些事情。

这是 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 的所有其他主题,并且我也遵循了本教程,但我真的找不到错误可能存在的差异。

编辑 2问题解决了。从一开始一切都运行良好,但由于某种原因,我在用数据填充对象和 putExtra 之间添加了更多代码,所以基本上我发送了一个空对象¯\_(ツ)_/¯

4

1 回答 1

0

首先避免传递位图,它们可能太大并将字符串提取"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);

这个奇怪的事情已经发生在我身上,我用这种方式解决了它。

于 2017-03-03T12:56:04.253 回答