Search code examples
androidandroid-viewpagerandroid-loadermanagerandroid-loader

How to restart Loader in a ListFragment from a FragmentActivity tha uses ViewPager?


I have a ViewPager FragmentActivity that holds 3 tabs, Each one of the tabs is a ListFragment that has a Loader. In the initialization of this activity all the loaders load, so far so good.

I implemented a public method refresh() in the fragment that restarts the loader: getLoaderManager().restartLoader(0, null, this);

When I call it from the parent activity it throws illegalStateException Fragment not attached to Activity. Any ideas how can I restart the loader?

Edit:

My activity extends SherlockFragmentActicity and in it I have an adapter that extends FragmentPagerAdapter to menage the tabs in the pager.

public class UserPageFragmentActivity extends SherlockFragmentActivity{
   ...

    mTabsAdapter.addTab(mTabHost.newTabSpec(TAB_CHANNELS).setIndicator("Following"),
            UserPageListFragmentChannels.class, null);
   ...

     public void refresh(){

           switch (mTabHost.getCurrentTab()){
                     case CHANNELS:
                              ((UserPageListFragmentChannels)mTabsAdapter.getItem(CHANNELS)).refresh();
                              break;
        ...
           }

     }

}

now the tab fragment is:

public class UserPageListFragmentChannels extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Void> {

...
    public void refresh(){
        getLoaderManager().restartLoader(0, null, this);        
    }
...


}

Solution

  • So after digging a little bit more I found the solution here from "barkside": Update data in ListFragment as part of ViewPager

    I implement it the same in my activity's refresh():

    UserPageListFragmentChannels fragment =  
                  (UserPageListFragmentChannels) getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.pager+":0"); 
              if(fragment != null)  // could be null if not instantiated yet 
              { 
                 if(fragment.getView() != null)  
                 { 
                    // no need to call if fragment's onDestroyView()  
                    //has since been called. 
                    fragment.refresh(); // do what updates are required 
                 } 
              }