javaandroidkotlinactivity-result-apiactivityresultcontracts

How to construct PickVisualMediaRequest for ActivityResultLauncher


I am trying to use the Activity Result APIs to handle the picking of a single photo for an app I am developing. I am trying to use one of the predefined contracts to keep things simple. So, I am attempting to use the ActivityResultContracts.PickVisualMedia() contract.

I am setting the Activity Result Launcher up as follows:

private ActivityResultLauncher<PickVisualMediaRequest> pickVisualMediaActivityResultLauncher;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    pickVisualMediaActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.PickVisualMedia(),
            this::onPickVisualMediaActivityResult
    );
}

And I am attempting to construct a PickVisualMediaRequest and launch the Activity Result Launcher here:

private void onSelectNewPhotoButtonClick() {
    PickVisualMediaRequest request = new PickVisualMediaRequest.Builder()
            .setMediaType(new ActivityResultContracts.PickVisualMedia.ImageOnly())
            .build();
    pickVisualMediaActivityResultLauncher.launch(request);
}

Issue is that Android Studio is complaining about ActivityResultContracts.PickVisualMedia.ImageOnly() not having proper visibility to be used, even though it is a valid VisualMediaType and the docs imply that it should be used this way: enter image description here

I can't really find any code samples on this particular scenario. Am I missing something? Does the API have a visibility defect or am I just dumb today?


Solution

  • After some help from CommonsWare, I determined that setMediaType() accepts a Kotlin object instance. So, the above bad function I had should be:

    private void onSelectNewPhotoButtonClick() {
        ActivityResultContracts.PickVisualMedia.VisualMediaType mediaType = (ActivityResultContracts.PickVisualMedia.VisualMediaType) ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE;
        PickVisualMediaRequest request = new PickVisualMediaRequest.Builder()
                .setMediaType(mediaType)
                .build();
        pickVisualMediaActivityResultLauncher.launch(request);
    }
    

    Android Studio complains about the type casting, but the code does compile and work as expected. Very bizarre.

    enter image description here

    enter image description here