user1923613
user1923613

Reputation: 636

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().

Upvotes: 10

Views: 29264

Answers (2)

Steve Benett
Steve Benett

Reputation: 12933

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.

Upvotes: 9

Shreshth Kharbanda
Shreshth Kharbanda

Reputation: 1838

You should try:

this.getId();

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

Upvotes: 10

Related Questions