gpt4 book ai didi

java - OncreateView 中的意外 NPE

转载 作者:行者123 更新时间:2023-11-29 23:44:39 25 4
gpt4 key购买 nike

我正在将数据从 Activity 发送到 fragment 并使用以下代码启动 fragment :

if (conversation != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ConversationFragment conv = new ConversationFragment();
frgObj = ConversationFragment.newInstance(conversation);
fragmentTransaction.replace(R.id.container, frgObj, "ConversationFragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
}

这里是我的 fragment 方法:

   static Conversation activeConversation;
public static ConversationFragment newInstance(Conversation _activeConversation){
ConversationFragment fragment = new ConversationFragment();
activeConversation=_activeConversation;
return fragment;
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_conversation, container, false);

...
Long conversationId = activeConversation.getId();
...
}

这在我的模拟器和测试设备上运行良好。但是当我查看商店崩溃报告时,我看到一些用户得到了 activeConversation.getId()

的空指针异常

这个问题可能是什么原因造成的,我该如何解决?

最佳答案

您应该始终使用 fragment 参数将数据传递给 fragment 。

这是您的应用程序崩溃的情况。用户使用您的 fragment 启动 Activity 。您通过参数将数据传递给 fragment 。实例已正确创建。现在用户转到其他一些应用程序,而您的应用程序转到后台。在某个时候,如果用户不再使用它,Android 系统将终止 Activity,但它会记住用户离开的位置,以便在用户返回时重新创建状态。在这种情况下,它知道要创建哪个 Activity 和哪个 fragment 。在这种情况下,它将使用默认构造函数来创建 fragment 。由于默认构造函数不填充静态 activeConversation,应用程序在 onCreateView 中崩溃。

相反,在您的 newInstance 中,将此信息放入参数包中,然后在您的 onCreateView 中使用它。更多信息在这里:https://developer.android.com/reference/android/app/Fragment#setArguments(android.os.Bundle)

fragment 的参数在 fragment 重新创建期间保持不变。

关于java - OncreateView 中的意外 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51553218/

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