Search code examples
androidandroid-intentparcelableandroid-bundle

Bundle loses its values between activities


I use the following codes to start activity with bundle extras data, and I can see the data has saved in Intent extras:

public static Intent newIntent(Context packageContext, AccountItem account, TransactionItem transaction) {
    Bundle args = new Bundle();
    args.putParcelable("arg_key_account", account);
    args.putParcelable("arg_key_transaction", transaction);
    args.putInt("test_key", 18);

    Intent intent = new Intent(packageContext, TransactionConnectActivity.class);
    intent.putExtra("arg_key", args);
    intent.putExtra("test_key", 21);
    return intent;
}

enter image description here

However, when I try to get bundle extras data from intent, the bundle has no data:

protected void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    Intent intent = getIntent();
    if (intent != null) {
        int test = intent.getIntExtra("test_key", -1);
        Bundle args = intent.getExtras().getBundle("arg_key");
    }
    ...
}

enter image description here

The custom object have implement Parcelable, and all members have been written to parcel. and I have read these questions and answers, but still cannot figure out where i am wrong?


Solution

  • To make sure Parcelable works, should use correct method to writeToParcel and createFromParcel, otherwise Android cannot retrieve data correctly which will cause createFromParcel returns a null object.

    As for this issue here, I use writeValue to parcel a String member, which must use writeString.