Creating a Custom ActivityResultContract and Using in Jetpack Compose
In this post, let us see how we can create a custom contract for calling Google’s AutoComplete Android APIs for searching locations. It will be a short post without explaining how to get a map API key. You can check your Google cloud console to get a key. You can check this link to set up a places API for Android and add the compose dependencies.
In the past, we used registerActivityForResult and had to use request codes but it becomes difficult to manage codes when you have to register many calls. The recommended way is using the ActivityResultContract which takes an input I and output O.We will override the methods createIntent and parseResult. Below is the code for the custom contract.
Here, we use Context as input and Place as the output. A Place is thus the return type of the parseResult method. The intent object is created by using AutoComplete.IntentBuilder and passing the fields that we are interested in getting from the place result.
Calling the Intent in Compose
Compose provides the composable rememberLauncherForActivityResult and passing our created contract as the contract.
Note that you can also use our contract in an Android views project by calling registerActivityForResult and passing our contract.Clicking the button launches the AutoCompleteActivity and selecting a searched location returns the result.