java—parcelable对象中属性的空值为什么?

raogr8fs  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(306)

我有以下几点 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` 
6l7fqoea

6l7fqoea1#

在parcelable构造函数中,您需要从包中读回数据。

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

b5buobof2#

首先,在您的构造函数中,似乎您正在尝试将所有属性写入包,但据我所知,它们尚未设置;你可能是想看包裹里的东西?现在我不确定这个包裹到底是什么,但我在想它的一些属性,比如类?如果是这样,java就不是通过引用传递的。这意味着仅仅修改传递给您的方法的值不会修改真正的包的值,您必须返回修改后的包

c0vxltue

c0vxltue3#

您应该在构造函数中使用readint而不是writeint(对于其他字段是etc)

相关问题