How can I access getSupportFragmentManager() in a fragment?
I

22

215

I have a FragmentActivity and I want to use a map fragment within it. I'm having a problem getting the support fragment manager to access it.

 if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map1)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }

            // create marker
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude)).title("Hello Maps ");

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(latitude, longitude)).zoom(15).build();

            googleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            // adding marker
            googleMap.addMarker(marker);
Ibnrushd answered 27/11, 2013 at 8:44 Comment(0)
E
357

You can directly call

getParentFragmentManager()  

to get the fragment manager. Note that getFragmentManager() also works but has been marked as deprecated.

Enzymology answered 27/11, 2013 at 8:51 Comment(18)
when i click first time it work but after that going on some other fragment again i click on this it shows blank page..Ibnrushd
This is an overhead. See my answer below... getFragmentManager() is really all you need.Spiry
You don't need global mContext variable here, just use getActivity() wherever in your code you need it. Please edit your answer so you don't misguide people in wrong direction.Chiron
@Chiron : Please keep in mind that there are chances where getActivity() can return null. For example, if the fragment is detached and if inside the fragment, if we call getActivity() it will return null. So if we are going for any async operations, its better to take it in a variable and use it.Enzymology
No It won't, if you call it after certain method. Even you don't call getActivity, you can still get FragmentManager by just calling getFragmentManager() method of Fragment. You can do async operations only when Fragment is attached as AsyncTask relies on Activity life cycle but if you want to do something in background and outside of Activity lifecycle then better use Service. In that case ones you started the service, you don't need to control it. What you recommending to people is a bad practice. You should not have a global variable until or unless you REALLY need it.Chiron
@Chiron Its all because of your lack of knowledge. First of all Async operations doesn't mean you need to use an Async task, it can be a thread. Second thing, Async task doen't relies on activity, what it is depended on is the UI thread to post the results back; to make it understandable for you, just try to create and use Async task inside your service, it will work (Don't tell service is activity.. :P). If I need some async operations to be performed, how can I use Service Sir? Perhaps you should understand the service uses the same UI thread and so it wont be async anymore.Enzymology
@Chiron Now the actual use of this is, for example, if you are calling a webservice from fragment, and if the user navigates away from fragment in between the service call to another fragment and when the service completes and if you try to open or show a dialog in your first fragment using getActivity(), it will result in nullpointer, you can try this example.Enzymology
@Chiron If you dealt with large projects involving frequent fragment transactions without stoping the user for background async operations, probably you will understand what I'm saying. Goodluck with your method and happy coding and keep this null pointer in mind.Enzymology
Yes i have worked on big projects with more than 30 fragments in it and I am talking from my experience. I don't do hacks or avoid best practices to just avoid NullPointerException, I fix them. Happy coding to you as well. Cheers!!Chiron
@Chiron Do you think creating a reference variable is a hack? Big project doesnt mean it should contains many fragments. What I meant is their transaction complexities and frequencies in async manner wrt broadcasts, events etc. Happy coding...sorry.....happy fixing....Enzymology
No its not but you are avoiding best practices here. If you don't believe me just send an email with this code to any Google developer and see what they have to say about it. Cheers!!Chiron
@Chiron I'll believe you if you provide proofs to justify your comment. I've made my justification for why I used this. And I'm sure no one will mark this as a hack since I'm just using a reference variable to hold the context and am also pretty sure that it will not result in any memory leak since its life time will be that of the fragments. So please define "Avoiding best practice".Enzymology
Best practices teaches us, don't use global variable, until or unless you REALLY need one. Let me explain you why your answer is wrong. First if you need a FragmentManager, you can simply call getFragmentManager() anytime. Don't believe me, test it by yourself. You don't even need a Context variable for that, forget about global variable. Secondly, getActivity() only returns null in case of where Fragment is detached and the function you using is onActivityAttached(). There is no chances on earth getActivity() will return null after this method. Don't believe me test it by yourself.Chiron
@Varundroid. I agree to the fact that we can call getFragmentManager() anytime. If you can send me your email Id, I can send u sample code to prove that there are chances on earth for getActivity() to return null.Enzymology
@EldhoseMBabu how can method getSupportFragementManager be called without a class's, reference name?Krystlekrystyna
@androidplusios.design You need to call getFragmentManager() and not getSupportFragementManager inside your fragment. getFragmentManager() is an instance function of Fragment class and so u can call it inside a Fragment and it will take the containing Fragment class's current instance reference.Enzymology
Really helpful in implementing fragment inside a fragment. Saved my day. Thanks alot.Kc
This now also works : requireActivity().getSupportFragmentManager()Ern
S
85

All you need to do is using

getFragmentManager()

method on your fragment. It will give you the support fragment manager, when you used it while adding this fragment.

Fragment Documentation

Spiry answered 27/11, 2013 at 9:0 Comment(5)
This should be the accepted answer, it is not advised to keep a reference to the parent activity as suggested by the first answer.Owing
@Spiry this is a perfect answer and should be the accepted answer.Chiron
This will return android.app.Fragment. In some cases, you need android.support.app.v4.Fragment so it will not work all the time.Ether
how to fix this? i think i need the support.app.v4.Fragment oneNewsletter
This will return the appropriate FragmentManager. If in an android.support.app.v4.Fragment, it will return the same thing as the getSupportFragmentManager() method in Activity would. The reason the method is called simply getFragmentManager() in this case is because it is not ambigious, unlike in the case of Activity.Aribold
C
56

Simply get it like this -

getFragmentManager() // This will also give you the SupportFragmentManager or FragmentManager based on which Fragment class you have extended - android.support.v4.app.Fragment OR android.app.Fragment.

OR

getActivity().getSupportFragmentManager();

in your Fragment's onActivityCreated() method and any method that is being called after onActivityCreated().

Chiron answered 4/7, 2014 at 2:48 Comment(5)
This is what I use, although I'm quite new to Android development and I'm not sure if it's the correct way of doing things.Hardin
@codecaster you can get the FragmentManager using getFragmentManager() method of Fragment itself as well. I have edited my answer.Chiron
I have a project here that did weird things until I swapped getFragmentManager() for getActivity.getSupportFragmentManager().Hardin
Hmmm strange. Never ran into an issue like this so far but none of the above solutions is bad so you can use whatever works for you.Chiron
I've looked deep into the classes from all the way. Seems this is the best solution who uses android.support.v4.app.FragmentGuard
A
21

Kotlin users try this answer

(activity as AppCompatActivity).supportFragmentManager
Aylmar answered 21/9, 2017 at 8:26 Comment(1)
Good thing you have put this here, otherwise it would drive me crazy TySurbase
M
16

if you have this problem and are on api level 21+ do this:

   map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();

this will get the map when used inside of a fragment.

Mitch answered 16/2, 2016 at 19:50 Comment(2)
I tried all of the suggested code fixes above, but couldn't get any of them to work. getChildFragmentManager() did the trick! Thx.Atelier
how about api level below 21? Api level 19 for example?Colp
J
15

in java you can replace with

getChildFragmentManager()

in kotlin,

childFragmentManager
Jaramillo answered 28/2, 2020 at 7:45 Comment(0)
M
14

The simple new way of doing it in kotlin

requireActivity().supportFragmentManager
Morphosis answered 1/6, 2020 at 18:39 Comment(0)
E
9

getFragmentManager() has been deprecated in favor of getParentFragmentManager() to make it clear that you want to access the fragment manager of the parent instead of any child fragments.

Simply use getParentFragmentManager() in Java or parentFragmentManager in Kotlin.

Ellmyer answered 1/2, 2021 at 16:43 Comment(0)
S
7

My Parent Activity extends AppCompatActivity so I had to cast my context to AppCompatActivity instead of just Activity.

eg.

FragmentAddProduct fragmentAddProduct = FragmentAddProduct.newInstance();
FragmentTransaction fragmentTransaction = ((AppCompatActivity)mcontext).getSupportFragmentManager().beginTransaction();
Shaveling answered 4/7, 2016 at 16:7 Comment(1)
((AppCompatActivity) mContext) part was EXACTLY what i was looking for. Thank you!Topi
D
6

You can use getActivity().getSupportFragmentManager() anytime you want to getSupportFragmentManager.

hierarchy is Activity -> fragment. fragment is not capable of directly calling getSupportFragmentManger but Activity can . Thus, you can use getActivity to call the current activity which the fragment is in and get getSupportFragmentManager()

Druce answered 30/1, 2015 at 2:55 Comment(0)
T
4
((AppCompatActivity) getActivity()).getSupportFragmentManager()
Toniatonic answered 25/5, 2019 at 9:22 Comment(0)
I
3

do this in your fragment

getActivity().getSupportFragmentManager()
Interposition answered 27/5, 2017 at 17:28 Comment(0)
S
3

getActivity().getFragmentManager() This worked or me.

Also take a look at here.

Scarborough answered 27/4, 2018 at 18:17 Comment(0)
F
3

if you are using fragment manager in the activity

getSupportFragmentManager()

supportFragmentManager

if you are using fragment manager in the fragment

childFragmentManager
Flung answered 8/8, 2022 at 5:28 Comment(0)
K
2

The following code does the trick for me

 SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
    mapFragment.getMapAsync(this);
Kayceekaye answered 7/3, 2018 at 22:43 Comment(0)
G
2

You can use childFragmentManager inside Fragments.

Glorygloryofthesnow answered 19/7, 2019 at 10:2 Comment(0)
R
1

You can simply access like

Context mContext;

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

mContext = getActivity();

}

and then use

FragmentManager fm = ((FragmentActivity) mContext)
                        .getSupportFragmentManager();
Ries answered 29/12, 2016 at 10:47 Comment(0)
L
1

Some Kotlin code to use supportFragmentManager inside a Fragment.

  override fun onCreateView(
      inflater: LayoutInflater,
      container: ViewGroup?,
      savedInstanceState: Bundle?

  ): View? {

    super.onCreateView(inflater, container, savedInstanceState)
    val rootView = inflater.inflate(R.layout.fragment_home, container, false)

    // ....

    if (rootView.home_play_btn != null) {

      rootView.home_play_btn.setOnClickListener {
        val fragment: BaseFragment = ListFragment.newInstance()
        val fragManager: FragmentManager = (activity as AppCompatActivity).supportFragmentManager
        fragManager.beginTransaction()
            .replace(R.id.content_home_frame, fragment, TAG).commit()

      }
Laid answered 9/1, 2020 at 0:13 Comment(0)
D
1

Best way to get fragmentManager inside of a fragment is to call the new method

getParentFragmentManager()

or use the property access syntax in kotlin files

parentFragmentManager

this specifies the fragmentManager that is to be loaded (choosing between child and parent fragments )

Dryer answered 16/12, 2021 at 8:20 Comment(0)
C
0

Try this:

private SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());
Comestible answered 17/7, 2014 at 9:7 Comment(2)
What is your requirement, I think your requirement is to define a pager inside another pager with the help of fragments inside fragments..! i.e. you need to swipe a layout inside a swippable layout?Comestible
the reason @V.J. asked you to expand your answer is because a line of code is not a good quality answer. Many people other than the original asker of the question will see your answer and may want to use it to solve their own problem. It would be helpful to those users if you actually explained what the original problem was with the question, why it didn't work, and why you solution does work.Divinize
M
0

getSupportFragmentManager() used when you are in activity and want to get a fragment but in the fragment you can access

getSupportFragmentManager()

by use another method called getFragmentMangaer() works the same like getSupportFragmentManager() and you can use it like you used to:

fragmentTransaction =getFragmentManager().beginTransaction();
Mandrel answered 15/8, 2017 at 5:6 Comment(0)
S
0

I use this code and it's work:

val profileFragment = ProfileFragment()
val fragmentManager = parentFragmentManager
fragmentManager.beginTransaction().apply {
                            replace(R.id.fragment_main, profileFragment, ProfileFragment::class.java.simpleName)
                            addToBackStack(null)
                            commit()

the R.id.fragment_main is the main layout that you used. if you used main activity, then you can give id for the layout.

Supportable answered 5/7, 2022 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.