0

I have an app in which i am showing Custom Dialog and Toast message all works fine but app is sometime getting crash and showing logg error as "Fragment LayoutTwo{820b58c} not attached to Activity".Please help.

code:-

CustomerTicketDialogClass ctdc = new CustomerTicketDialogClass(getActivity(), 
            "network failure", 
            getResources().getString(R.string.NetworkError_Message), "LayoutTwo");
ctdc.show();
ctdc.setCanceledOnTouchOutside(false);
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
Niraj
  • 31
  • 1
  • 10

1 Answers1

-1

This error happens due to the combined effect of two factors:

The HTTP request, when complete, invokes either onResponse() or onError() (which work on the main thread) without knowing whether the Activity is still in the foreground or not. If the Activity is gone (the user navigated elsewhere), getActivity() returns null. The Volley Response is expressed as an anonymous inner class, which implicitly holds a strong reference to the outer Activity class. This results in a classic memory leak. To solve this problem, you should always do:

Activity activity = getActivity();

if(activity != null){

// etc ...

}

and also, use isAdded() in the onError() method as well:

@Override

public void onError(VolleyError error) {

Activity activity = getActivity(); 
if(activity != null && isAdded())
    mProgressDialog.setVisibility(View.GONE);
    if (error instanceof NoConnectionError) {
       String errormsg = getResources().getString(R.string.no_internet_error_msg);
       Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
    }
}

}

chandrakant sharma
  • 1,334
  • 9
  • 15