0

I have fragment class in which I'm making an Async call. Now I'm making a method in Fragment class and I want this method to be invoked in MainActivity class. The MainActivity class dynamically loads the Fragment class.

The code snippets are :

public class MainHandlerFragment extends Fragment{

   public boolean getDetails(User user){
      if(user==null)
         return false;
      else 
         return true;
  }
}

MainActivity.java

I am calling

 MainHandlerFragment fragment = new MainHandlerFragment(user);
   fragment.getDetails();   // But i am getting NullPointerException.

How to invoke the method of fragment class in MainActivity?

Akshay
  • 2,506
  • 4
  • 34
  • 55
anand
  • 1,711
  • 2
  • 24
  • 59

3 Answers3

2

Here's an example:

public class MyFragment extends Fragment {

    public static final String TAG = “MyFragment.TAG”;

    // Implementation follows.

}

public class MyActivity extends Activity {

    public MyFragment getMyFragment() {
        final FragmentManager manager = getFragmentManager();
        return (MyFragment) manager.findFragmentByTag(MyFragment.TAG);
    }

    public void invokeMethodFromMyFragment() {
        final MyFragment fragment = getMyFragment();
        if (null != fragment) {
            fragment.getDetails();
        }
    }

}

This assumes your MyFragment transaction included the MyFragment.TAG tag when commited.

Tadej
  • 2,901
  • 1
  • 17
  • 23
  • ok.. If i want to pass one object from Fragment to MainActivity how can i do that.. For ex User object i am passing from fragment to MainActivity @curtisLoew – anand Sep 18 '14 at 09:40
  • 1
    Read [the docs](http://developer.android.com/training/basics/fragments/communicating.html), it's exactly what you're looking for. – Tadej Sep 18 '14 at 09:48
  • Thanx..@curtisLeow. Really documentation part was very helpful and it worked. – anand Sep 18 '14 at 11:10
0
FragmentClass fragment = (FragmentClass) getFragmentManager().findFragmentById(
                R.id.ll_fragment1);
        fragment.fragmentMethod();

try this in your activity you can call the method of fragment from your activity

0

Try to call the

fragment.getDetail(user);

after completing the Transaction using add() or replace() method of the Transaction Class .... and the commit() it also.

Hope it will work.

mithileshssingh
  • 275
  • 3
  • 16