[Android] Usual problem with asnychronous requests: Updating a no-longer-existing Fragment

If you are using asynchronous requests (e.g. AsyncTasks, Services+BroadcastReceivers, android-volley, android-async-http or any other flavour), this scenario may sound familiar to you:

1.- in the Activity’s onCreate() or onResume() method, an asynchronous HTTP request is sent
2.- User quickly destroys the Activity (for example, rotating the phone)
3.- Response to the request made in step 1 arrives, the onResponse/onHandleIntent callback is fired, but the Activity/Fragment is no longer existing, because you have destroyed it in step 2. so BOOM!!! App crashes, giving your users this undesirable “Has stopped unexpectedly” message, and generating such a bad experience with your app.

Typical error message:

java.lang.IllegalStateException Fragment MyFragment not attached to Activity

The simplest and smartest solution for that is using Fragment’s isAdded() method:

if(isAdded()){
mGridView.setVisibility(GridView.INVISIBLE);
// … any other update you need to do in the views
}

So if you reproduce the steps above, isAdded() will return false and application won’t crash.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s