Ahmed Bakhet
Ahmed Bakhet

Reputation: 3234

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, ...

Upvotes: 5

Views: 3381

Answers (2)

Burak Dizlek
Burak Dizlek

Reputation: 5125

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...
}

Upvotes: 1

m3g4tr0n
m3g4tr0n

Reputation: 671

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

Upvotes: 14

Related Questions