Search code examples
javaandroidandroid-intentactivityresultcontracts

Android. How to disable multiple selection of files via intent?


I'm trying to select file with intent Intent.ACTION_OPEN_DOCUMENT. Here is my code:

ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.OpenDocument(), uri -> {
    if (uri != null) {
     
    }
});

And then:

launcher.launch(mimeTypes);

This works, however I would like to only allow the user to select one file. But at the moment, when the file explorer opens, the user can select multiple files. I would like to disable multiple selection, is this possible?

Please, help me.


Solution

  • you need to add

      intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
    

    on your intent ie setting multiple to false

    here is a snippet

    ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.OpenDocument(), uri -> {
        if (uri != null) {
         
        }
    });
    

    // method to launch the file picker with single selection

    private void openDocumentPicker(String[] mimeTypes) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
    // Disabling  multiple selection
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false); 
    
        launcher.launch(intent);
    }
    

    // Usage and setting the mimetype

    String[] mimeTypes = {"image/*", "application/pdf"}; 
    openDocumentPicker(mimeTypes);