Domanda

I have a fragment which works fine basically. In the onResume method I perform an api call to get fresh data when ever a the user gets to the activity/fragment.

public void onResume(){
    super.onResume();

    //in pseudo
    do async call 
       success callback
          update ui

       failure callback
          update ui
}

This works fine most of the time. However I experience a problem when the user navigates back to the parent activity, before the update ui method has finished. The update ui just sets some text views.

E.g. when the user navigates to the activity and the fragment the above onResume is called. Immediately the users goes back to the parent activity. The async call and update ui isn't finished yet and I get:

FATAL EXCEPTION: main Process: com.project.foobar, PID: 4405 java.lang.IllegalStateException: Fragment MyDetailFragment{41ebb478} not attached to Activity

This is thrown in the update ui method after success callback. I use square's retrofit to manage api calls. And again, this just happens when update ui has not finished. When I wait for it to finish and go back everything is fine.

Any ideas what might be wrong?

È stato utile?

Soluzione

Either abort the async operation when you navigate away from the fragment, or simply check to see if the fragment is still attached with isAdded() when you attempt to update the UI. If it's not attached just ignore the result and do not touch the views.

The first option will probably be the most correct but also the hardest to implement. The second option is perfectly fine in my opinion unless you're doing some really heavy and long running stuff in the background thread.

Altri suggerimenti

When I want the asynchronous task to finish anyway: imagine my onPostExecute does store data received and then call a listener to update views so, to be more efficient, I want the task to finish anyway so I have the data ready when user cames back. In this case I usually do this:

@Override
protected void onPostExecute(void result) {
// do whatever you do to save data
  if (this.getView() != null) {
      // update views
  }
}

Fragment MyFragment not attached to Activity

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top