Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loader doesn't start after calling initLoader()?

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

like image 800
user291701 Avatar asked Apr 25 '12 18:04

user291701


4 Answers

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

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

like image 144
Alex Lockwood Avatar answered Sep 24 '22 23:09

Alex Lockwood


In my experience it never worked unless I used forceLoad().

You may find the answer to this previous question helpful: Loaders in Android Honeycomb

like image 40
nohawk Avatar answered Sep 22 '22 23:09

nohawk


Three important points regarding Loaders are:

  1. Always Use forceLoad() method while initialising Loaders. For Example:

    getLoaderManager().initLoader(500, null, mMyCallback).forceLoad();
    
  2. Always implement onStartLoading(). This function will automatically be called by LoaderManager when the associated fragment/activity is being started.

  3. Make sure the ID of the loader is unique otherwise new Loader will not be called.

If there is still a problem you can check the state of loader by calling the isStarted() method.

like image 4
Tarun Deep Attri Avatar answered Sep 20 '22 23:09

Tarun Deep Attri


You need to keep a reference to the instance of the loader you create in the method onCreateLoader. Then, to refresh it, call yourLoader.onContentChanged();

like image 2
Snicolas Avatar answered Sep 24 '22 23:09

Snicolas