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
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
/** * The main activity that communicates with the fragment(s) * @author Elisha Chirchir - Simple Developer * @since - 2014 * */ public class MainActivity extends Activity implements NewsItemsFragment.OnNewsItemSelectedListener { private NewsItemsFragment mItemsFragment; @Override public void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.main); //Instantiate some stuff here like view components mItemsFragment = new NewsItemsFragment(); //Now you can set the fragment to be visible here setFragment(mItemsFragment); } public void setFragment(Fragment frag) { FragmentManager fm = getFragmentManager(); if (fm.findFragmentById(R.id.container) == null) { fm.beginTransaction().add(R.id.container, frag).commit(); } } //Override the method here @Override public void onNewsItemPicked(int position) { //Do something with the position value passed back Toast.makeText(activity, "Clicked "+ position, Toast.LENGTH_LONG).show(); } } |
Now we can create our Fragment class here – the order is up to you really!
NewsItemsFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
/** * Fragment that inflates a list view to display news headlines * @author - Elisha Chirchir - Simple Developer Blog * @since - 2014 */ public class NewsItemsFragment extends ListFragment implements AdapterView.OnItemClickListener { Activity activity; public static List newsHeadlines = new ArrayList(){{ add("Android Is Awesomerrrrrrrrrrrrrrrrrrr"); add("A teenager asks Miss America To Prom and gets suspended"); add("The Congress in The History of the United States is.."); add("How To Drive Safely When No One else Is."); add("Learn How To Program On Your Own"); add("How To Communicate Between Fragments and Activities"); add("What to do when you have nothing to do"); add("The next big thing is here - your awesome app!"); }}; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = activity; } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); ArrayAdapter adapter = new ArrayAdapter(activity, R.layout.simple_row_item, newsHeadlines); setListAdapter(adapter); getListView().setOnItemClickListener(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ return inflater.inflate(R.layout.head_lines_fragment, container, false); } @Override public void onItemClick(AdapterView< ?> parent, View view, int position, long id) { Toast.makeText(activity, "Clicked "+ position, Toast.LENGTH_LONG).show(); try{ ((OnNewsItemSelectedListener) activity).onNewsItemPicked(position); }catch (ClassCastException cce){ } } public interface OnNewsItemSelectedListener{ public void onNewsItemPicked(int position); } } |
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!
tainy
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
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
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
That is true. Interfaces just makes everything easier to do when dealing with different activities and fragments. Thank you for visiting.
Kevin
Bruh… Try using a static method.
Ishan
Using static methods is a deprecated approach now
Fragment Kullanımı – Fragmentlar Arası İletişim |
[…] 2. http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/ […]
maor
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
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.
Matt
I have similar situation witch viewPager. I have main activity which contains toolbar spinner and fragments with method that displays charts. I want to pass main activity spinner value to the fragment method but whatever I do it throws me a null point exception.
Have you any idea what may I do wrong?
Elisha Chirchir
I wonder what the exception is you are getting? You should get the spinner value at any given time and pass it as an extra to the fragment then get that same value from within the fragment!
Wil
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?
saubhagya das
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
Rohit
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
How To Set Layout Visibility In Android | MY NEWS
[…] 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 …… […]
How To Set The Layout In Android | MY NEWS
[…] 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 …… […]
mike
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
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
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.
Fragment.. | ggokul
[…] http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/ […]
Android Interface Class for Fragment Communication | PCS
[…] 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 […]
Payal Garg
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
geethtadevi
really well said about Communication between fragment and activity in android.
Leonardo Correa
Thanks ! Very helpfull !
henry
nyc tut
luke
Hi,
I’m building an app, and I’m pretty new at this whole coding and stuff. Here’s my problem. I’m using Firebase to store my data on. The data that I have is Albums and Tracks. Now, in my AlbumsFragment, I managed to show data like ListView, but I don’t know how to allow user when he clicks on of the Albums items , to open a new Activity and show Tracks of that Album. Can you help me?
Vinay Kumar
Hi,
I want to access fragment from the activity so i created the one activity and one base fragment for access the other fragments. if communicate the server from the base fragment then all base fragment’s Xml components is going to be null. What is this?
Please provide me the some better solution.
med
Hello , i need to know how navigate from a fragment to another activity by a button in the fragment , beacause i tryed with method Intent but there’s many errors and exceptions
sanjay
i have buttons in main activity layout and in fragment layout there is no buttons how can i fire events in fragment class by using main activity buttons .I can switch from main activity to multiple fragments but when I am in fragment i am unable to enter values by using main activity buttons.
Sangith Priya
Thanks for your great article. 🙂
– Priya