Call Method in Fragment from Unrelated Class

Tricky question here, but I will try and be clear.

Class A: extends FragmentActivity and has the FragmentManager

Class B: extends Fragment and has the fragment's UI

Class C: Unrelated Class

    public class A extends FragmentActivity{
        Fragment fragment = new FragmentActivity();
    }

    public class B extends Fragment{
        public void methodToBeCalled(){
             //do something
}
    }

    public class C{
        //call B's methodToBeCalled() from here
        //note it is not static
    }

What I want to do is call a method which is located in Class B from Class C. Any ideas how I could go about doing this?

A solution would be a way to run this code from Class C:

B fragment = (B) getFragmentManager().findFragmentById(R.id.b);

This does not work (it compiles, but the if statement is always false):

    if (A.getCurrentFragment() instanceof B) {
        B fragment = (B) A.getCurrentFragment();
        fragment.methodToBeCalled();
    }

Solved

Pass the context of FragmentActivity to the Class C, using this context you can get the fragment manager and then you can find the fragment using the fragment id or tag.

FragmentManager fm = context.getSupportFragmentManager();
//tag should same as what you gave while adding the fragment
FragmentB fb=(FragmentB)fm.findFragmentByTag("tag"); 
// call public methods of FragmentB
fb.CallFromClassC();

Use

FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)

or

FragmentTransaction.replace (int containerViewId, Fragment fragment, String tag)

to set tag for a fragment

Then check fragment instance by tag:

A.getCurrentFragment().getTag().equals("btag")

Step 1 : if class using AsyncTask:

Create a constructor into non-fragment class and parse Fragment Manager:

Step 2:

FragmentManager mFragmentManager;

    // create a constructor
    public NetworkMaster(Activity mMasterActivity){

        this.mFragmentManager = mMasterActivity.getFragmentManager();

    }// end constructor NetworkMaster

Step 3:

protected void onPostExecute(String result) {

            try {

                //ID should same as what you gave while adding the fragment
                SummaryFragment oSummaryFragment = (SummaryFragment)mFragmentManager.findFragmentById(R.id.content_frame); 

                // call public methods of SummaryFragment
                oSummaryFragment.responseFromSummaryUser(result);               

            } catch (Exception e) {
                e.printStackTrace();
            }

        }// end onPostExecute

Step 4: Class the non-fragment class from Fragment:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

NetworkMaster mNetworkMaster = new NetworkMaster(getActivity());
mNetworkMaster.runUserSummaryAsync();

}

Comments