Xaloju Xaloju - 3 months ago 39
Android Question

Why my app crash when I switch fragments fast?

My apps crash sometimes when I change the fragment with the navigationDrawer.
The fatal error isn't helping much, How can I solve this problem? Thx

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)


Fragment3 line170: onStart() listener

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

Answer

The reason for this crash is that the fragment is still executing code while it is already detached from your Activity.

In your case the Fragment is already switched to another Fragment when it reaches the getContext(). Because getContext() is looking for the Activity (which the fragment is no longer attached to) it will cause a nullpointer exception.

Try the following:

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