pick only documents types from storage using activity result API
Asked Answered
F

2

5

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

Forgive answered 25/12, 2021 at 14:52 Comment(2)
instead of '/' have you tried like 'application/pdf' ?Kerns
@Kerns this will allow only pdf file, I need all documents typesForgive
S
14

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

Schilt answered 25/12, 2021 at 15:13 Comment(1)
Please can you give example of mime-types ?Aside
C
1

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...
}
Cloots answered 25/7, 2023 at 7:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.