gpt4 book ai didi

java - Bundle 返回 long 而不是 Parcelable

转载 作者:搜寻专家 更新时间:2023-11-01 08:26:14 24 4
gpt4 key购买 nike

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 对象,所以我在 onCreate 中从 bundle 中获取它> 像这样:

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

Bundle bundle = this.getArguments();

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

...
}

注意:currentObject是fragment中定义的私有(private)CustomParcelable,objectID是fragment中定义的私有(private)long,KEY是public final stringfragment 中定义。

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

Is the data passed cor数据是否正确传递?究竟是什么导致 currentObject 为空?

最佳答案

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

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

例如,如果您看到 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();
}

在 fragment A中

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

希望这能消除你的疑虑

关于java - Bundle 返回 long 而不是 Parcelable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44695937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com