4

So I am trying to launch the intent Intent.ACTION_OPEN_DOCUMENT. I first tried with startActivityForResult but I noticed it was depreciated so I tried to find another way to do this. So I found the registerForActivityResult method but it turns out it must run after onCreate() has finished :

Note: While it is safe to call registerForActivityResult() before your fragment or activity is created, you cannot launch the ActivityResultLauncher until the fragment or activity's Lifecycle has reached CREATED.

Since I am using Jetpack Compose and setContent is in onCreate() my Activity has actually never finished creating because all my Composables functions are run in the setContent of my MainActivity

So how can I achieve this ?

1 Answer 1

11

Using the latest version of activity-compose you can use rememberLauncherForActivityResult() to register a request to Activity#startActivityForResult.

Something like:

val result = remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) {
    result.value = it
}

Button(onClick = { launcher.launch(arrayOf("application/pdf")) }) {
    Text(text = "Open Document")
}

result.value?.let {
   //...
}
4
  • To Android Studio result.value is undefined reference
    – ScarySneer
    Jun 22, 2021 at 9:48
  • @ScarySneer Did you add: val result = remember { mutableStateOf<Uri?>(null) }? result is a MutableState<Uri?>. Jun 22, 2021 at 9:52
  • Yes I did. Sorry, actually result is defined, what android studio complains about is value. The actual error is Undefined reference: value
    – ScarySneer
    Jun 22, 2021 at 9:53
  • 1
    So turns out it's my fault, instead of using val result = remember { mutableStateOf<Uri?>(null) } I used val result by remember { mutableStateOf<Uri?>(null) }. So now I am wondering what is the difference between these two since in compose docs they say "These declarations are equivalent, and are provided as syntax sugar for different uses of state"
    – ScarySneer
    Jun 22, 2021 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.