Search code examples
android-fragmentsactionbarsherlockandroid-listfragment

commit fragment from onLoadFinished within activity


I have an activity which loads a data list from the server using loader callbacks. I have to list out the data into a fragment which extends

SherlockListFragment 

i tried to commit the fragment using

Fragment newFragment   = CategoryFragment.newInstance(mStackLevel,categoryList);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();

in onLoadFinished and it gives an IllegalStateException saying

java.lang.IllegalStateException: Can not perform this action inside of onLoadFinished

I have referred the example in actionbar sherlock, but those examples have loaders within the fragments and not the activity.

Can anybody help me with this o that I can fix it without calling the loader from the fragment!


Solution

  • Atlast, I have found a solution to this problem. Create a handle setting an empty message and call that handler onLoadFinished(). The code is similar to this.

    @Override
    public void onLoadFinished(Loader<List<Station>> arg0, List<Station> arg1) {
        // do other actions
        handler.sendEmptyMessage(2);
    }
    

    In the handler,

    private Handler handler = new Handler()  { // handler for commiting fragment after data is loaded
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 2) {
                Log.d(TAG, "onload finished : handler called. setting the fragment.");
                // commit the fragment
            }
        }
    }; 
    

    The number of fragments depend on the requirement.

    This method can be mainly used in case of stackFragments, where all fragments have different related functions.