为什么我在快速切换 Fragment 时应用程序会崩溃?

8

有时在使用导航抽屉切换片段时,我的应用程序会崩溃。 致命错误并没有提供太多帮助,我该如何解决这个问题?谢谢。

FATAL EXCEPTION: main
     Process: acr.acr_app, PID: 29425
   java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
   at android.view.ViewConfiguration.get(ViewConfiguration.java:359)
   at android.view.View.<init>(View.java:3656)
   at android.view.View.<init>(View.java:3751)
   at android.view.ViewGroup.<init>(ViewGroup.java:492)
   at android.widget.LinearLayout.<init>(LinearLayout.java:200)
   at android.widget.LinearLayout.<init>(LinearLayout.java:196)
   at android.widget.LinearLayout.<init>(LinearLayout.java:192)
   at android.widget.LinearLayout.<init>(LinearLayout.java:188)
   at android.widget.TableRow.<init>(TableRow.java:61)
   at acr.acr_app.MyFragment3$2.onChildAdded(MyFragment3.java:170)
   at com.google.android.gms.internal.zzaer.zza(Unknown Source)
   at com.google.android.gms.internal.zzagp.zzSu(Unknown Source)
   at com.google.android.gms.internal.zzags$1.run(Unknown Source)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:135)

第3片段第170行:onStart()监听器

  tableRow = new TableRow(getContext());
  tableRow.setLayoutParams(new TableLayout.LayoutParams(
  TableLayout.LayoutParams.WRAP_CONTENT,
  TableLayout.LayoutParams.WRAP_CONTENT, 1.0f));

尝试将 getContext() = this 更改为并重新构建项目。 - Tai Nguyen
你的 getContext 正在返回 null。 - peeyush pathak
1
谢谢帮忙,但我无法在我的片段中使用“this”,这就是为什么我使用了getContext()。是否有另一种解决方案可以使用onAttach/onDetach方法? - Xaloju
你可以使用"YourFragmentName.this"代替"this"。然而,这可能无法解决你的问题。请查看下面的答案,以获取可能的解决方案。 - MrJM
2个回答

6
这个崩溃的原因是该片段在已经从您的Activity中分离出来时仍在执行代码。
在您的情况下,当片段到达getContext()时,它已经切换到另一个片段。因为getContext()正在寻找Activity(而片段已经不再附加到其中),这将导致空指针异常。
请尝试以下操作:
 if(isAdded()){
    tableRow = new TableRow(getContext());
    tableRow.setLayoutParams(new TableLayout.LayoutParams(
    TableLayout.LayoutParams.WRAP_CONTENT,
    TableLayout.LayoutParams.WRAP_CONTENT, 1.0f));
 }

这个好像可以了!不再崩溃了,但我需要进行更多测试来确保。谢谢。 - Xaloju

0
你的碎片(Fragment)使用的是什么工作模式,是:replace还是showhide?如果你快速切换,它会崩溃,因为当它附加到FragmentActivity时,你的碎片尚未完成初始化。尝试像这样做:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接