android – FragmentManager and androidx FragmentManager-ThrowExceptions

Exception or error:

I’m trying to setup in my app that is using androidX.

My problem is that when I try to work with PlaceAutocompleteFragment I get errors because it is a fragment from android.app.fragment and my parent fragment is an androidx fragment: androidx.fragment.app.Fragment so it uses a androidx.fragment.app.FragmentManagerinstead of a android.app.FragmentManager.

How can I work with “old” fragments in androidX?

How to solve:
  1. Add this to dependencies:
    implementation 'androidx.appcompat:appcompat:1.0.2'.
  2. Add this: import androidx.fragment.app.FragmentTransaction;.
  3. Switch your activity extends from Activity to AppCompatActivity.
  4. Change from getFragmentManager() to getSupportFragmentManager().

This will fix your issue.

###

If you are using the new libraries then only use those, don’t combine them bacause yo can run into more problems. Now for your problem go to your fragment and just change the import form:

import android.app.fragment

To:

import androidx.fragment.app.Fragment

That should solve your problem.

###

There is not any need to get the FragmentManager directly from the Activity because a replacement method has been provided in the Fragment called getParentFragmentManager:

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

From the docs for the deprecated getFragmentManager:

 * @deprecated This has been removed in favor of <code>getParentFragmentManager()</code> which
 * throws an {@link IllegalStateException} if the FragmentManager is null. Check if
 * {@link #isAdded()} returns <code>false</code> to determine if the FragmentManager is
 * <code>null</code>.

The docs for the replacement method getParentFragmentManager:

 * Return the FragmentManager for interacting with fragments associated
 * with this fragment's activity.  Note that this will available slightly
 * before {@link #getActivity()}, during the time from when the fragment is
 * placed in a {@link FragmentTransaction} until it is committed and
 * attached to its activity.
 *
 * <p>If this Fragment is a child of another Fragment, the FragmentManager
 * returned here will be the parent's {@link #getChildFragmentManager()}.
 *
 * @throws IllegalStateException if not associated with a transaction or host.

Just take care to check isAdded to make sure that the FragmentManager is not null.

Leave a Reply

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