Search code examples
javaandroid-studioandroid-fragmentsandroidxdeprecation-warning

AndroidX Activity Result API onActivityCreated Deprecated


After implementing the below dependency in app level Gradle

implementation "androidx.fragment:fragment:1.3.0-beta02"
implementation "androidx.activity:activity:1.2.0-beta02"

I found the below warning in my fragment in onActivityCreated method

Overrides deprecated method in 'androidx.fragment.app.Fragment'

What might be the new way of implementing this method. Below is my onActivityCreated method

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
}

I am using the dependency for requestPermissionLauncher.


Solution

  • You can check out the changelog/deprecation warning here in more detail: https://developer.android.com/jetpack/androidx/releases/fragment#1.3.0-alpha02

    Specifically

    The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate().

    Changing your code to the example below should remove the deprecation warning:

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
    }