I get the Non-static method 'getSupportFragmentManager()' cannot be referenced from static context
error for the following code:
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentActivity;
.
.
.
public class MedicalInformationFragment extends Fragment implements FragmentNameProvider, ConfirmDialogFragment.ConfirmDialogListener{
.
.
.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Entered: onCreate");
first = true;
if(getArguments() != null) {
petId = getArguments().getInt(PET_ID_KEY);
Log.d(TAG, "Pet ID is: " + petId);
sMedicalInformationViewModel = ViewModelProviders.of(this).get(MedicalInformationViewModel.class);
FragmentManager fm = FragmentActivity.getSupportFragmentManager();
if(fm != null) {
thisFragment = fm.findFragmentById(R.id.fragment_container);
Log.d(TAG, "thisFragment is: " + thisFragment);
}else{
Log.d(TAG, "Error: fm == null");
}
}else{
Log.d(TAG, "Error: getArguments() == null");
}
}
.
.
.
}
However, the keyword 'static' is never used in the class, anywhere.
I am following the API for using getSupportFragmentManager(). I had used getFragmentManager but was told that android.app.Fragment
was deprecated in API level 28.and to use the Support Library Fragment for consistent behavior across all devices and access to Lifecycle
, but found that this package is part of the Android support library which is no longer maintained. The support library has been superseded by AndroidX which is part of Jetpack
.
So, here I am, following what I believe are the directives of the Android API and getting an error that I don't understand. What would generate this error when the 'static' keyword is not used?
You are calling an instance method (getSupportFragmentManager()
) on a class (FragmentActivity
), not on an instance. The "static context" is FragmentActivity
.
To get a FragmentManager
for your Fragment
, try getParentFragmentManager()
:
FragmentManager fm = getParentFragmentManager();
If that does not seem to exist, you are on an older version of the AndroidX libraries, before that method existed. In that case, use getFragmentManager()
:
FragmentManager fm = getFragmentManager();