返回到 parent activity 的 Parcelable class 为空

Parcelable class returned to parent activity is null

我在 tutorial.I 中学习 android 开发时制作的这个书店应用程序已经为这个问题苦苦挣扎了 6 个小时。出于某种原因,当我在 child Activity 上设置结果时,当我检查 Book Parcelable class 的 toString 时,它会打印出 logcat 中的预期内容。我通过在 onActivityforResult:

中执行此操作,在 parent 中启动 Activity for Result:

            Intent addIntent = new Intent(this, AddBookActivity.class);
            startActivityForResult(addIntent, ADD_REQUEST);

然后将 Parcelable class 书寄回(在 child activity 中完成)

            Intent returnIntent = new Intent();
            returnIntent.putExtra(BOOK_RESULT_KEY, newBook);
            setResult(RESULT_OK, returnIntent);
            Log.i("intent get", returnIntent.getParcelableExtra(BOOK_RESULT_KEY).toString());
            finish();

在这种情况下,toString() returns 在应用程序中输入书名和价格 correctly.Here 是我在 parent [=46] 中检索意图的方式=]:

if(requestCode == ADD_REQUEST){
        if(resultCode == RESULT_OK) {
            Book newBook = intent.getParcelableExtra(AddBookActivity.BOOK_RESULT_KEY);
            Log.i("book", newBook.toString());
            shoppingCart.add(newBook);

然而它总是打印出 "null null" 而不是 "TITLE_OF_BOOK PRICE_OF_BOOK"。 Whosebug 上的许多帖子都描述了类似的问题,但没有任何效果。我也尝试在发送和接收意图时使用捆绑包。

我很确定我的书 class 已经正确实施了 parcelable,但这里仅供参考。作者也是一个 parcelable class。

public class Book implements Parcelable{
int id;

public String title;

public Author[] authors;

public String isbn;

public String price;

public Book(int id, String title, Author[] author, String isbn, String price) {
    this.id = id;
    this.title = title;
    this.authors = author;
    this.isbn = isbn;
    this.price = price;
}

private Book(Parcel in){
    this.id = in.readInt();
    this.authors = in.createTypedArray(Author.CREATOR);
    this.title = in.readString();
    this.isbn = in.readString();
    this.price = in.readString();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeString(title);
    dest.writeTypedArray(authors, 0);
    dest.writeString(isbn);
    dest.writeString(price);
}

public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
    @Override
    public Book createFromParcel(Parcel source) {
        return new Book(source);
    }

    @Override
    public Book[] newArray(int size) {
        return new Book[size];
    }
};

@Override
public int describeContents() {
    return 0;
}

@Override
 public String toString() {
    return title + " " + price;
}
}

我真的不知道为什么它总是显示空,发送意图和使用parcelables的整个想法似乎很容易理解。

编辑:添加 Log.i("book", newBook.title) 时,出现此错误:

Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {...BookStoreActivity}: java.lang.NullPointerException:println needs a message

然后错误指向该日志行。

似乎Book的所有属性在收到时都设置为null,但在发送时却没有。

您的图书 object 无法自行重建,因为您从包裹中读取值的顺序与写入顺序不同。

在您的 writeToParcel() 方法中,您写的是第二个标题,第三个是作者。然而,在您的地块构造函数中,您正在阅读作者第二,标题第三。您需要按照写入顺序从包裹中读取值。

尝试一下,让我知道结果如何。