Search code examples
androidandroid-gradle-pluginandroid-appcompatandroidx

AndroidX ActivityResultContracts package not found / class not found


According to this documentation from Google about launching an activity to get a result:

While the underlying startActivityForResult() and onActivityResult() APIs are available on the Activity class on all API levels, it is strongly recommended to use the Activity Result APIs introduced in AndroidX Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02.

I want to let my users take a photo from within my app and get that photo data back to my app. I was going to use the old startActivityForResult() but this new method looks like it will solve lots of problems and be more reliable, so I wanted to give it a try. I'm supposed to be able to call registerForActivityResult() and pass it a built-in contract for taking a picture called ActivityResultsContracts.TakePicture:

this.registerForActivityResult(new ActivityResultContracts.TakePicture(), ...);

But I get: error: package ActivityResultContracts does not exist

I've added this to my app/build.gradle:

// original include
//implementation 'androidx.appcompat:appcompat:1.1.0'

// suggestion from Google documentation
//implementation 'androidx.appcompat:appcompat:1.2.0-alpha02'

// AndroidStudio suggested a newer version was available
implementation 'androidx.appcompat:appcompat:1.2.0-beta01'

I tried the alpha02 and the beta01 and neither of them seem to have the classes referred to in the documentation.

When I try to import the class manually at the top of my java file, AndroidStudio doesn't think the package exists either. It should be androidx.activity.result.contract.ActivityResultContracts.TakePicture, but this is what I see:

screenshot of Android Studio auto-complete package list in import statement

I'm using gradle 3.5.3 if that matters at all. (Whenever I try to upgrade to the latest gradle, my project goes insane, so I've just been staying with the version that works.)


Solution

  • From the quoted documentation:

    it is strongly recommended to use the Activity Result APIs introduced in AndroidX Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02.

    Neither of those are in your dependencies, at least the portion from your question. You have been manipulating appcompat, not activity or fragment.

    Add either or both of:

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

    (or any higher versions)