gpt4 book ai didi

java - Parcelable 对象中的属性为 NULL 值。为什么?

转载 作者:行者123 更新时间:2023-12-01 15:12:42 24 4
gpt4 key购买 nike

我有以下 Recipe 类,它正在实现 Parcelable 类。但是,当我将对象从一个类传递到另一个类时,其属性的值为 null。为什么?

食谱类别:

package mobile.bh.classes;

import java.util.ArrayList;

import mobile.bh.activities.MethodStep;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;

//simple class that just has one member property as an example
public class Recipe implements Parcelable {
public int id;
public String name;
public ArrayList<Ingredient> ingredients;
public ArrayList<MethodStep> method;
public String comment;
public String image;
public Bitmap image2;

public Recipe(){}
/* everything below here is for implementing Parcelable */

// 99.9% of the time you can just ignore this
public int describeContents() {
return 0;
}

// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(name);
out.writeList(ingredients);
out.writeList(method);
out.writeString(comment);
out.writeString(image);
}

// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Recipe> CREATOR = new Parcelable.Creator<Recipe>() {
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}

public Recipe[] newArray(int size) {
return new Recipe[size];
}
};

// example constructor that takes a Parcel and gives you an object populated with it's values
private Recipe(Parcel in) {
in.writeInt(id);
in.writeString(name);
in.writeList(ingredients);
in.writeList(method);
in.writeString(comment);
in.writeString(image);
}
}

通过intent发送对象

    Intent i = new Intent(context,RecipeInfoActivity.class);
i.putExtra("recipeObj", recipe);

接收对方对象

Recipe p = (Recipe) getIntent().getParcelableExtra("recipeObj");

但是p.name的值为null

最佳答案

在 Parcelable 构造函数中,您需要从 Parcel 中读回。

private Recipe(Parcel in) {
id = in.readInt();
name =in.readString();
ingredients = in.readList();
method = in.readList();
comment = in.readString();
}

关于java - Parcelable 对象中的属性为 NULL 值。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12111667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com