Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loader not being called when screen orientation change

I facing a bit of trouble when using AsyncTaskLoader and the screen orientation changes. Let me give you some context on how my app is structured: I have a very simple app which fetches results from a url and displays it. The app consists of one FragmentActivity and three Fragments. My three fragment are as follows:

  • First fragment is an edittext and a button to submit input.
  • Second fragment shows a loading spinner
  • Third fragment replaces the loading-fragment when the data is fetched to show the results.

The AsyncTaskLoader is used to load data from either a content provider (if it is cached) or from the network.

Everything works great until the screen oreintaion changes! I looked at the output of LoaderManager.enableDebugLogging(true) and it seems the source of the problem is that LoaderCallbacks.onLoadFinished doesn't get called in my activity.

Here is a piece of the code that launches the loader:

/* This function is defined in the "first" fragment in an interface and
 * implemented in the activity */ 
@Override
public void onFormSubmission(String word) {                     

    showLoadingFragment();

    if ( mWord == null || mWord.equals(word) ) {
        getSupportLoaderManager().initLoader(0, word, this);
    } else {
        getSupportLoaderManager().restartLoader(0, word, this);
    }

    // Store the word
    mWord = word;
}

The code that displays the result:

@Override
public void onLoadFinished(Loader<Bundle> loader, Bundle data) {
    // Validation and other stuff

      ResultFragment fragment = new ResultFragment();

      // Add the fragment to the 'result_fragment_container' FrameLayout
      getSupportFragmentManager()
            .beginTransaction()
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
            // Replace loading fragment with the result
            .replace(R.id.result_fragment_container, fragment)
            .commitAllowingStateLoss(); 
}

Approaches I tried but failed:

  • Setting setRetaininstance(true) in fragments.
  • Setting android:configChanges="orientation|keyboardHidden|keyboard" in the manifest.

I'm out of ideas, so any help would be appreciated.

like image 415
Maher4Ever Avatar asked Apr 25 '12 18:04

Maher4Ever


1 Answers

You should put getSupportLoaderManager().initLoader(0, null, this); in the onActivityCreated method. The initLoader will create or reconnect with a loader if it already exists

like image 66
Quanturium Avatar answered Sep 18 '22 11:09

Quanturium