Loader doesn't start after calling initLoader()?

user291701 picture user291701 · Apr 25, 2012 · Viewed 11.7k times · Source

I have a fragment, and want to start a loader when a button is clicked:

public class MyFragment extends Fragment {

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

        Button btn = ...;
        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                getLoaderManager().initLoader(500, null, mMyCallback);
            }
        });
    }  

    private LoaderManager.LoaderCallbacks<String> mMyCallback = new  LoaderManager.LoaderCallbacks<String>() {

        @Override
        public Loader<String> onCreateLoader(int arg0, Bundle arg1) {
            Log.e(TAG, "LoaderCallback.onCreateLoader().");
            return new MyLoader(getActivity());
        }
    }
}

public class MyLoader extends AsyncTaskLoader<String> {
    public MyLoader(Context context) {
        super(context);
    }

    @Override
    public String loadInBackground() {
        Log.e(TAG, "Hi, running.");
        return "terrific.";
    }
}

After clicking the button, I can see my callback's onCreateLoader method called, but the created loader never actually starts. Do we need to call forceLoad() on the loader itself to get it to actually start? None of the sample posts do this,

Thanks

Answer

Alex Lockwood picture Alex Lockwood · Aug 23, 2012

You need to implement onStartLoading() and call forceLoad() somewhere in the method.

See this post for more information: Implementing Loaders (part 3)