片段事务.replace()方法抛出空对象引用 [英] Fragment Transaction .replace() method throwing null object reference
问题描述
我有一个程序,其默认UI是 ViewPager
,带有 TabLayout
。 MainActivity
是 CoordinatorLayout
。 Viewpager
, AppBarLayout
和 TabLayout
全部包含在一个 RelativeLayout
我打算用它作为一个容器,用于将主UI换成不同的视图。
I have a program whose default UI is a ViewPager
with a TabLayout
. The MainActivity
is a CoordinatorLayout
. The Viewpager
, AppBarLayout
, and TabLayout
are all wrapped in a RelativeLayout
that I intend to use as a container for swapping the main UI out for a different view.
托管在其中一个 ViewPager
视图中是一个按钮。此按钮通过名为 HelperLinkerListener
的接口与 MainActivity
进行通信,其中 MainActivity
工具。我知道接口连接正确,因为我已经通过logcat测试了它。
Hosted in one of the ViewPager
views is a button. This button communicates with MainActivity
via an interface called HelperLinkerListener
, which the MainActivity
implements. I know that the interface is wired up correctly because I've tested it via logcat.
我喜欢让按钮换掉我的包装 RelativeLayout
新片段。以下是我的 onHelperLinkerClick()
的当前内容:
I'd like to have the button swap out my wrapper RelativeLayout
for a new fragment. Here is the current content of my onHelperLinkerClick()
:
Fragment fragment = new GsonPlaceholder();
Bundle bundle = new Bundle();
bundle.putParcelable("char",charGson);
fragment.setArguments(bundle);
Log.d("logtest", "onHelperLinkerClick: " + bundle.getParcelable("char"));
FragmentTransaction ft = fm.beginTransaction();
ft.remove(getSupportFragmentManager().findFragmentById(R.id.container));
ft.commit();
这里,charGson是一个正确定义的实现Parcelable的类。该行
Here, charGson is a properly defined class implementing Parcelable. The line
ft.remove(getSupportFragmentManager().findFragmentById(R.id.container));
抛出以下空指针异常:
java.lang.NullPointerException:尝试从空对象
引用的字段'int
android.support.v4.app.Fragment.mContainerId'中读取
java.lang.NullPointerException: Attempt to read from field 'int android.support.v4.app.Fragment.mContainerId' on a null object reference
我不清楚如何解决这个问题。有什么想法?
It's unclear to me how to fix this problem. Any thoughts?
推荐答案
在我的情况下,尝试删除空
。您可以插入代码
In my case exactly the same exception was thrown on the attempt to remove fragment that was null
. You can insert a code
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().remove(null).commit();
并查看错误日志。问题是异常将不会抛出此字符串,但稍后会在Android源代码内部稍后抛出,您不会看到哪些代码字符串是异常的原因。
and see your error log. The problem is that exception will be throwed not on this string, but little bit later somewhere inside of Android sources and you do not see which of your code strings was the reason of the exception.
这篇关于片段事务.replace()方法抛出空对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!