How To Communicate Between Fragments and Activities in Android

Welcome to: how to communicate between fragments and activities in your android applications. If you have not done so already, please check out my previous post on dynamic layout design using weights and fragments that I wrote yesterday! In the above linked post, I briefly talk about how to solve the problem of dealing with different device sizes by letting the android system adjust accordingly! In today’s post, we are going to take a quick look at how fragments can communicate back to the activity – basically how they can call back and forth to pass information when needed. Also, if you ever use fragments, you should always avoid trying to let fragments communicate with one another – it is a bad idea (will explain this later).

Download my new app I created just for this!

Since I was getting this question a lot, I decided to create a simple android app that shows you how to communicate between fragments and activities – with example code.

Wait, there is more: you can choose to listen to it because it can read the tutorial to you as you sit back and enjoy. Download the app now for free and NO ads.

Android Fragments Ultimate Guide App

how to communicate between fragments and activities

 

As shown in the image above, you can simply tell the intent of the arrows. Communication start from the fragment to the activity and then from the activity back to the fragment or to another fragment if you have more than one fragment displayed. So, how do you do this? Not difficult to say the least – as we will see soon!

How To Communicate Between Fragments and Activities – Example

Step One

The first thing while creating your app that uses fragments is to create  your layouts. Once you have created your layouts which could be a list view or anything you want, you can then create your Fragment class.

Inside your onCreateView method of your fragment, you should inflate that view – again, a list view is a good example here. You normally return a view inside this method. Now, using a list view for example, you would probably like to do something whenever a user selects an item from that list like pop open a dialog to let them confirm their actions or load a whole new view to display the details for that particular item. So, how do you accomplish that?

You simply want to implement an OnClickListener then override its onClick method (this depends on what type of view you have – which could be a grid view or just a list view). Overriding such a method provides you with certain arguments like position – which is important when you really want to deal with particular items in a list and you can then pass the value back to the activity!

Step Two

The second step after inflating your view and implementing a click listener (as an example), you want to define an interface and then create a method – always remember than interface methods do not have bodies in them – it is the responsibility of the implementing class to override them and do what they want with them. You can define your interface from within the fragment class or as a standalone class in your project src folder.

Step Three

The third step is to implement that interface in your main activity. You will do something along the lines of MainActivity extends Activity implements FragmentOne.OnContactSelectedListener  – from there on, you will have to override the method you defined earlier (from the fragment) in your activity. If your method inside your fragment expected an integer argument, remember to define it exactly as it is in your activity(same signature).

Step Four

Now that you have that covered, here comes the beauty of interfaces – whenever a user clicks an item, you can grab the position of that item (from the onClick method) and pass it back to the activity by simply calling the interface method. After that, you can pick it from the activity – inside the method you overrode and do some really awesome stuff with that position like query the database or get a value from a list array depending on which position you get back! Pretty cool right?

Let us try and create some stuff here.

MainActivity.java

Now we can create our Fragment class here – the order is up to you really!

NewsItemsFragment.java

Summary of How To communicate between fragments and activities

The reason why fragments are very powerful is because they do almost anything you would do inside an activity. That being said, you could decide to instead of passing back just the position, you could do other manipulations like query the database to get the details from tables and then pass back the string value for the news articles. You can do a hell lot more to say the least.

As you can see, communication between fragments and activities is made so much easier through interfaces in Java and you can really do whatever you want. For example, inside the method we overrode in the activity, we could do something else like load a new fragment to display the details or even start a new intent to open a web page and other crazy things you can imagine!

This post is getting longer so I will halt it here for today and perhaps continue next time with other exciting stuff in android fragments! You can always visit the Google docs for more information on Fragments.

If you found this post helpful, p[ease consider sharing it with your friends using the buttons below! Thank you for stopping by and have fun coding!

Be The First To Get New Posts From Simple Developer…

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

18 Comments on “How To Communicate Between Fragments and Activities in Android

  1. tainy Reply

    June 18, 2014 at 10:23

    thanks for that. By reading the article, one problem come up to my mind that why we could not do the same thing without Interface. I really dont know the neccesity of using interface here. If we want to call the parent Activity, why not just get the Activity reference in onAttach and call by something like :
    (MyActivity)activity.some_method().
    could you please answer this?

    • Elisha Chirchir Reply

      June 18, 2014 at 2:24

      Well, there are many ways to do one thing. The point of using interfaces in java is mainly flexibility in implementation. It enables you to reuse fragments (the main point of having fragments in the first place). If you create a method in the activity, you cannot reuse it when you want to do something different with a given fragment. You can read more here.
      http://developer.android.com/training/basics/fragments/communicating.html

      • tainy Reply

        June 19, 2014 at 1:34

        oh yes. I just got to know that for I am using one fragment across two of my activities. And if I dont use interface, maybe there will be very ugly instanceof operator and class cast.

        • Elisha Chirchir Reply

          June 19, 2014 at 1:51

          That is true. Interfaces just makes everything easier to do when dealing with different activities and fragments. Thank you for visiting.

    • Kevin Reply

      May 20, 2015 at 2:01

      Bruh… Try using a static method.

      • Ishan Reply

        August 31, 2016 at 9:19

        Using static methods is a deprecated approach now

  2. […] 2. http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/ […]

  3. maor Reply

    February 18, 2015 at 11:22

    hi.
    first of all, its a gr8 tutorial! thanks!

    -i’m trying to implement this logic with an interface in my app, i have an activity that contains a viewPager that shows fragments, each fragment contains a check box, i am trying to receive the check box status in the main activity, how do i do that?

    • Elisha Chirchir Reply

      March 3, 2015 at 2:45

      Just create an interface in your fragment then implement it in your activity and when a user checks the box, call the interface method inside the fragment to notify the activity of the event. I will email you a better approach.

  4. Wil Reply

    February 26, 2015 at 2:28

    Thanks for the article!

    The question I have is can I connect both listview and viewpager (within fragment) to a mainactivity (with navigation drawer) to another fragment?

  5. saubhagya das Reply

    March 7, 2015 at 4:57

    Dear Friend,
    That was a good post. Its been some time I have following you.
    I have written a Post on this can you check and comment please.
    http://infobloggall.com/2014/06/22/communication-between-activity-and-fragments/

    Regards,
    Saubhagya Das

  6. Rohit Reply

    May 19, 2015 at 9:12

    I found the above article very informative and I have a quick question .
    Could you please tell me how to highlight the selected item in the navigation drawer .

    Thank You

  7. […] How To Communicate Between Fragments and Activities in Android – Welcome to: how to communicate between fragments and activities in your android applications. If you have not done so already, please check out my previous post on …… […]

  8. […] How To Communicate Between Fragments and Activities in Android – Welcome to: how to communicate between fragments and activities in your android applications. If you have not done so already, please check out my previous post on …… […]

  9. mike Reply

    July 11, 2015 at 10:52

    Really helpful! I have implemented the interfaces and works very well. I have a tab fragment (viewpager) with a list view. When the user clicks the list I call a dialog frag from the main activity that and when the dialog success button is clicked I want to delete the item. I have the interfaces from each frag and the main activity has the implementation. How can I delete from the list in tab frag from main activity..you elude to it in your post. Best

    • Elisha Chirchir Reply

      July 14, 2015 at 1:47

      When the OK button is clicked in the dialog fragment, you can keep track of the id of the item clicked and if the data is stored in the database, you can simply perform a db delete statement through the Model class. If it is just inside a local list that stores your times, you simply delete from your adapter. Let me know if this helps.

    • Elisha Chirchir Reply

      August 13, 2015 at 4:33

      Just pass the id of the selected item (or actually position from the list) to the activity. If I were you, I would let the fragment handle all that for you instead of depending on the activity for such trivial task.

  10. […] links: Android Interface class for fragment communication on YouTube Android Interface class for fragment communication on simpledeveloper Android Interface class for fragment communication on kb4dev Android Interface class for fragment […]

  11. Payal Garg Reply

    August 12, 2016 at 6:13

    Thanks a lot.I was getting mad as I was supposed to enhance a code made on this pattern.Now I know how to do it

Leave a Reply

Your email address will not be published. Required fields are marked *