Good all the time of day.

I can’t catch a bug in the application, in the Genymotion emulator, on the Nexus 5 phone it works perfectly, but ACRA from other users constantly pours java.lang.NullPointerException error reports.

Fragment.java

684 @Override 685 protected void onPostExecute(List<ObjectPlane> list) { 686 super.onPostExecute(list); 688 if (list == null || list.size() == 0) { 689 getActivity().runOnUiThread(new Runnable() { 690 @Override 691 public void run() { 692 progressDialogDismiss(); 693 setErrorTextAndButton(); 694 } 695 }); 696 } else { 697 if (adapter == null) { 698 adapter = new ObjectPlaneAdapter(getActivity().getApplicationContext(), list); listView.setAdapter(adapter); adapter.getFilter().filter(editText.getText().toString()); getQueryFromServer(); } else { adapter.notifyDataSetChanged(); getQueryFromServer(); } } if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(false); } progressDialogDismiss(); } 

Here is what ACRA sends:

 STACK_TRACE = java.lang.NullPointerException at ru.koltsovo.www.koltsovo.Fragment.Fragment$parsingXML.onPostExecute(Fragment.java:698) at ru.koltsovo.www.koltsovo.Fragment.Fragment$parsingXML.onPostExecute(Fragment.java:491) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) at android.os.Handler.dispatchMessage(Handler.java:110) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5299) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641) at dalvik.system.NativeStart.main(Native Method) 
  • One more note - onPostExecute is called in the UI thread, so getActivity().runOnUiThread() Linsnias - temq
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

This happens if the user, for example, has returned to the previous fragment through the back-end, or turned off the application. As soon as the fragment gets detachable, the getActivity() method will start to return null , since after this fragment you don’t belong to any Activity either you store the Activity before a variable (this is a bad solution, but simple), or check if the fragment attaches to Activity , before using this Activity

    As @metalurgus correctly noted, getActivity() returns null if the fragment is not attached to an activit. Those. the task is completed when the fragment is no longer displayed.

    So add a check for this in onPostExecute()

     @Override protected void onPostExecute(List<ObjectPlane> list) { super.onPostExecute(list); if(!isAdded()) { return; } ... }