Bundle returns long 而不是 Parcelable

Bundle returns long instead of Parcelable

activityA 中我有一个 listview,其中的每一项都是一个自定义 Parcelable 对象。在 listViewItemClick 上,我显示了一个带有两个参数的 fragment,我用这种方法将其放入 bundle

public void openFragment(CustomParcelable parcelableObject, long objectID) {
    FragmentA fragmentA = new FragmentA();
    Bundle bundle = new Bundle();
    bundle.putParcelable(FragmentA.KEY, parcelableObject);
    bundle.putLong(FragmentA.KEY, objectID);
    fragmentA.setArguments(bundle);
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragmentContainer, fragmentA);
    transaction.commitAllowingStateLoss();
}

FragmentA 中,我需要使用选定的自定义 Parcelable 对象,所以我从 bundle 中的 onCreate 中获取它,如下所示:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = this.getArguments();

    currentObject = bundle.getParcelable(KEY);
    objectID = bundle.getLong(KEY);

    ...
}

注意:currentObject是[=17=中定义的privateCustomParcelable,objectID是[=17=中定义的private long],KEY是public final string中定义的fragment.

当我稍后在我的方法之一中使用 currentObject 时,它 returns NPE 因为 currentObject 为 null。调试时显示它获得了 Parcelable,但其值为 objectID.

数据是否传递正确?究竟是什么导致 currentObject 为空?

您必须为每个数据使用不同的密钥。因为 bundle 元素被处理为名称值对,一个键和对应的值,

你做的是对两个数据使用相同的密钥,所以第一个数据被第二个长数据覆盖,

例如,如果您看到 this,则表示 putParcelable

Inserts a Parcelable value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null.

你应该做的是

public void openFragment(CustomParcelable parcelableObject, long objectID) {
    FragmentA fragmentA = new FragmentA();
    Bundle bundle = new Bundle();
    bundle.putParcelable(FragmentA.KEY1, parcelableObject);
    bundle.putLong(FragmentA.KEY2, objectID);
    fragmentA.setArguments(bundle);
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragmentContainer, fragmentA);
    transaction.commitAllowingStateLoss();
}

在片段A中

currentObject = bundle.getParcelable(KEY1);
objectID = bundle.getLong(KEY2);

希望这能消除您的疑虑