Jetpack Compose Lauch Activity and Receive Result (Place Autocomplete example)

December 16, 2021
@Composable
fun test() {
    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        val data: Intent? = result.data
        when(result.resultCode) {
            Activity.RESULT_OK -> {
                data?.let {
                    val place = Autocomplete.getPlaceFromIntent(data)
                    Timber.d("place=${place.name}")
                }
            }
            AutocompleteActivity.RESULT_ERROR -> {
                // TODO: Handle the error.
                data?.let {
                    val status = Autocomplete.getStatusFromIntent(data)
                    Timber.e("error=${status.statusMessage}")
                }
            }
            Activity.RESULT_CANCELED -> {
                // The user canceled the operation.
            }
        }
    }

    fun launchAutocomplete() {
        val fields = listOf(GooglePlace.Field.ID, GooglePlace.Field.NAME)
        val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields)
            .build(context)
        launcher.launch(intent)
    }
}

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.