18

I am trying to call a method in an activty from a Fragment screen.

I have a method called myMethod() which is in an activity called MyActivity; I have a fragment called Screen1Fragment.

I would like to call MyActivity.myMethod() from inside the Screen1Fragment but I am not sure how to do this.

Previously the Screen1Fragment was an activity and so I was extending MyActivity so that I could directly call myMethod(). But I have had to change the activity to a fragment for sliding tabs usage.

Thanks in advance.

Android Learner
  • 219
  • 1
  • 2
  • 12

3 Answers3

47

Use getActivity() in your fragment.

MyActivity activity = (MyActivity) getActivity();
activity.myMethod();

if you are not sure if your fragment is attached to MyActivity then

 Activity activity = getActivity();
 if(activity instanceof MyActivity){
      MyActivity myactivity = (MyActivity) activity;
      myactivity.myMethod();
 }
Sipka
  • 2,291
  • 2
  • 27
  • 30
  • Hi, the first way gives me an error that cannot cast from FragmentActivity to MyActivity. The second way does not give me an error but it is not loading the method on button click. Do I just place the code inside the button on click. – Android Learner Nov 01 '13 at 12:33
  • 1
    Then you should extend your Activity from FragmentActivity instead of Activity. (public class MyActivity extends FragmentActivity {...) – Sipka Nov 01 '13 at 12:51
  • Hi, the first way was working great, but for some reason my application is now crashing when I try to use it. – Android Learner Nov 02 '13 at 15:34
  • Are you calling getActivity() after onAttach()? Are you sure it doesn't return null? Are you sure it is instance of MyActivity? Log these out, and you got your solution. Try using: Log.d("MyFragment", "getActivity(): "+getActivity()); before the casting – Sipka Nov 02 '13 at 15:52
  • Thanks for getting back. I am not sure how to use the log.d This is the code I am running: TestActivity activity = (TestActivity) getActivity(); activity.myMethod(); causes application to crash – Android Learner Nov 02 '13 at 15:55
  • Hi, if i put the method in my MainActivity and call the code ((MainActivity) getActivity()).myMethod(); then it works if I have the same method in my TestActivity and use the code ((TestActivity) getActivity()).myMethod(); the application crashes why is this? – Android Learner Nov 02 '13 at 16:10
  • I guess u attached your fragment to a MainActivity instead of TestActivity, so the instance returned by getActivity() is a MainActivity, and it cannot be casted to TestActivity. And btw you should use logging. It help debugging very much, see the exceptions, log variables, etc... google it. – Sipka Nov 02 '13 at 16:48
  • How do I attach my fragment to the Test Activity. Or how can i call the method inside TestActivity please. – Android Learner Nov 02 '13 at 16:54
  • Same as you did in MainActivity, but use the code in your TestActivity. – Sipka Nov 02 '13 at 16:59
  • I am not sure how I attached it, My MainActivity has public class MainActivity extends FragmentActivity implements ActionBar.TabListener { And TestActivity has public class TestActivity extends FragmentActivity implements OnClickListener { And GamesFragment public class GamesFragment extends Fragment implements OnClickListener { – Android Learner Nov 02 '13 at 17:01
  • Helpful... Thanks – Pooja Aug 24 '20 at 19:45
28

You should make your fragment totally independant of the activity you are attaching it to. The point of Fragments is that you can re-use them in different contexts with different activities. To achieve that and still being able to call methods from your Activity the following pattern in recommended in the official documentation.

In your fragment:

  • define a public interface with the method

    public interface MyFragmentCallback{
        public void theMethod();
    }
    
  • define a field and get a cast reference:

    private MyFragmentCallback callback;
    public void onAttach(Activity activity){
        callback = (MyFragmentCallback) activity
        super.onAttach(activity);
    }
    

In your Activity

  • implement MyFragmentCallback in the class definition.
  • implement theMethod() in your activity (Eclipse will ask you to do so)

Then, from your fragment, you can call callBack.theMethod()

The difference between this and simply calling your method on getActivity() is that your fragment is not paired with this specific activity anymore. So you may re-use it with other activity for example one for phones and the other for tablets.

znat
  • 13,144
  • 17
  • 71
  • 106
0

If the method is the static method of MainActivity, something like:

    public static void someMethod(){}

Then, it is pretty straightforward. Just call

   MainActivity.someMethod()

However, I guess what you really want is to access some function from the Activity class. Then you can use the following code in the Fragment view creater

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

        container.getContext().someMethod();

   }
Anson Yao
  • 1,544
  • 17
  • 27
  • 2
    IMO this is bad practice. 1. container might be null, and getContext() returns Context, which u still have to check if MyActivity instance. 2. You don't want to communicate with Activity via static methods, since then it's not possible to have 2 instances of that Activity. – Sipka Nov 01 '13 at 13:15
  • 1
    Good point. But I guess it is OK in this case. It seems the question owner wants some sliding tabs in the activity. We are pretty sure the activity is there. I am not suggesting to use a static method anyway. I am guessing what is the real question. – Anson Yao Nov 01 '13 at 13:23