【问题标题】:Android getParcelableExtra object always returns nullAndroid getParcelableExtra 对象总是返回 null
【发布时间】:2017-03-04 00:30:13
【问题描述】:

所以我试图将一个对象作为 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 的所有其他主题,并且我也关注了 this tutorial,但我真的找不到错误可能存在的差异。

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

【问题讨论】:

标签: android android-intent null parcelable extra


【解决方案1】:

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

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

【讨论】:

  • 试过了,不幸的是所有参数都为空。
  • 尝试不使用位图。
  • 我相信这是默认的,因为我没有设置它。
猜你喜欢
  • 2023-03-11
  • 2015-09-16
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 2018-01-16
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多