Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pick only documents types from storage using activity result API

I need to make the user able to pick only documents types (ex: pdf, docs, xls) from phone storage using the new Activity Result API, but the problem is that when I launch the contract like the following code

private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
    ...
}

fun pickDocument() = getContent.launch("*/*")

user become able to select any file type including images, videos, ...

like image 395
Ahmed M. Abdalla Avatar asked Aug 29 '26 15:08

Ahmed M. Abdalla


2 Answers

Use

ActivityResultContracts.OpenDocument() 

instead of

ActivityResultContracts.GetContent()

and pass the required mime-types in:

pickDocumentsContract.launch(arrayOf("mime-type-1","mime-type 2"))

example:

pickDocumentsContract.launch(arrayOf(
"application/msword", //.doc (Microsoft Word file)
"application/pdf" //.pdf (Pdf file)
))

You can find more mime types here : https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

like image 118
m3g4tr0n Avatar answered Sep 01 '26 08:09

m3g4tr0n


You can check mime types from here.

private val launcher = registerForActivityResult(
    ActivityResultContracts.OpenDocument()
) { uri ->
    uri?.let { fileUri ->
        //todo you have fileUri here
    }
}


fun startLauncher(){
    launcher.launch(arrayOf("application/pdf","image/*")) //todo you can add more mime-type here...
}
like image 44
Burak Dizlek Avatar answered Sep 01 '26 07:09

Burak Dizlek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!