4

I have a AsyncTaskLoader with a long running task, when, while the loader is running, my activity is being destroyed due to an orientation change, the onLoadFinished callback isn't called.

Can I somehow 'reattach' the loader to my new Activity / it's callback?

Here's my (simplified) Activity:

public class DashboardActivity extends BaseActivity {

StartupCallback startupCallback;
    boolean loading = false; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.empty_viewpager);
    startupCallback = new StartupCallback();

    if (!loading){
         getSupportLoaderManager().initLoader(GlobalApp.giveId(), null,
                startupCallback);
                 loading = true; 
    }
}


private class StartupCallback implements
        LoaderManager.LoaderCallbacks<Boolean> {
    @Override
    public void onLoadFinished(Loader<Boolean> loader, Boolean succ) {

        Log.d("LOG", "onLoadFinished"); 
    }

    @Override
    public Loader<Boolean> onCreateLoader(int id, Bundle args) {

        return new StartupLoader(getApplicationContext());
    }

    @Override
    public void onLoaderReset(Loader<Boolean> loader) {

    }
}

}

I can not just start another loader with a new callback because the loader does database stuff and two loader working on the same database will crash the app.

sebataz
  • 1,025
  • 2
  • 11
  • 35
fweigl
  • 21,278
  • 20
  • 114
  • 205
  • I think your problem is restarting activity. By default android recreate activity when you change orientation. To prevent this add read about android:configChanges here: http://developer.android.com/guide/topics/manifest/activity-element.html – Alexander Mikhaylov May 08 '13 at 12:17
  • Thanks, but as you said that's the default behaviour and I don't want to change it; stopping the Activity from restarting on orientation change might work here but bring me in trouble elsewhere where I might encounter the same problem. – fweigl May 08 '13 at 12:23
  • how looks your new StartupLoader? code? – drdrej Jul 30 '14 at 19:11

3 Answers3

9

During orientation change your Activity is destroyed and recreated, but the loaders are not.

It is worth noting, that a call to initLoader() does not necessarily starts another loader. If the loader adressed by the specific ID exists, it is reused by LoaderManager and your callbacks are reattached to it. So you can remove your (!loading) condition, and call initLoader in every onCreate() callback. Just make sure the loader's ID is the same.

See also Loader guide

alexei burmistrov
  • 1,417
  • 10
  • 13
1

From the documentation, as long as the id is the same as the one you first passed it, it should return the current loader rather than a new one: android docs

FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37
-8

Adding android:configChanges="orientation|screenSize" to my activity did the trick for me.

Corey Adler
  • 15,897
  • 18
  • 66
  • 80