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

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

我有以下几点 Recipe 类,它正在实现 Parcelable 班级。但是当我将对象从一个类传递到另一个类时,它的属性值是 null . 为什么?
配方类别:

  1. package mobile.bh.classes;
  2. import java.util.ArrayList;
  3. import mobile.bh.activities.MethodStep;
  4. import android.graphics.Bitmap;
  5. import android.os.Parcel;
  6. import android.os.Parcelable;
  7. //simple class that just has one member property as an example
  8. public class Recipe implements Parcelable {
  9. public int id;
  10. public String name;
  11. public ArrayList<Ingredient> ingredients;
  12. public ArrayList<MethodStep> method;
  13. public String comment;
  14. public String image;
  15. public Bitmap image2;
  16. public Recipe(){}
  17. /* everything below here is for implementing Parcelable */
  18. // 99.9% of the time you can just ignore this
  19. public int describeContents() {
  20. return 0;
  21. }
  22. // write your object's data to the passed-in Parcel
  23. public void writeToParcel(Parcel out, int flags) {
  24. out.writeInt(id);
  25. out.writeString(name);
  26. out.writeList(ingredients);
  27. out.writeList(method);
  28. out.writeString(comment);
  29. out.writeString(image);
  30. }
  31. // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
  32. public static final Parcelable.Creator<Recipe> CREATOR = new Parcelable.Creator<Recipe>() {
  33. public Recipe createFromParcel(Parcel in) {
  34. return new Recipe(in);
  35. }
  36. public Recipe[] newArray(int size) {
  37. return new Recipe[size];
  38. }
  39. };
  40. // example constructor that takes a Parcel and gives you an object populated with it's values
  41. private Recipe(Parcel in) {
  42. in.writeInt(id);
  43. in.writeString(name);
  44. in.writeList(ingredients);
  45. in.writeList(method);
  46. in.writeString(comment);
  47. in.writeString(image);
  48. }
  49. }

发送对象 intent ```
Intent i = new Intent(context,RecipeInfoActivity.class);
i.putExtra("recipeObj", recipe);

  1. 在另一边接收对象

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

  1. 但它的价值 `p.name` `null`
6l7fqoea

6l7fqoea1#

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

  1. private Recipe(Parcel in) {
  2. id = in.readInt();
  3. name =in.readString();
  4. ingredients = in.readList();
  5. method = in.readList();
  6. comment = in.readString();
  7. }
b5buobof

b5buobof2#

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

c0vxltue

c0vxltue3#

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

相关问题