Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ID of a fragment?

First of all, I followed this tutorial to create an activity with an actionbar+tabs. What this implementation does is that it has a fragment_container (just a linear layout) in the main_activity layout and it replaces it with a fragment depending on what tab is selected.

Now, I'm trying to add some fragment-to-activity communication but I'm getting a nullpointerexemption.

Here's my code:

com.mypackage.MAPFragment map_ =
(com.mypackage.MAPFragment) getFragmentManager().findFragmentById(R.id.map);
map_.ActivityToMapMethod();

The MAPFragment fragment inflates a xml layout that has a mapView with and id of map. I'm not so sure if the map id is what I'm supposed to be using. I've successfully done this before in another app but that time the fragment was added via xml, and not by using replace().

like image 849
user1923613 Avatar asked Mar 07 '13 17:03

user1923613


2 Answers

The findFragmentById() method gets a Fragment id out of a container if there actually a Fragment inside it. Otherwise you will get null back. findFragmentById(R.id.fragment_container) returns the Fragment inside the LinearLayout of your tutorial.

like image 179
Steve Benett Avatar answered Sep 22 '22 08:09

Steve Benett


You should try:

this.getId();

It worked for me and I hope it works out for you. Hope it helps! Good Luck!

like image 29
Shreshth Kharbanda Avatar answered Sep 19 '22 08:09

Shreshth Kharbanda