I am working on Android jetpack compose. I have bottom navigation and on an event going to an Activity. I want to recompose the screen when coming back to the previous screen so that the data refreshes.
I am working on Android jetpack compose. I have bottom navigation and on an event going to an Activity. I want to recompose the screen when coming back to the previous screen so that the data refreshes.
What you need to do is change a state in your composable when you receive the answer from the activity... something like this:
First, make your activity (I'm assuming you already have one) return the data as of it would return to another activity, using setResult method.
class ResponseActivity : AppCompatActivity() {
// Call this function to return a String to the caller
private fun sendActivityResult(text: String) {
val anInt = intent.getIntExtra(EXTRA_INT, -1)
setResult(RESULT_OK, Intent().apply {
putExtra(EXTRA_STRING, "$text: $anInt")
})
finish()
}
companion object {
const val EXTRA_INT = "anInt"
const val EXTRA_STRING = "anString"
}
}
The activity above receives an Int as input param and returns a String to the caller.
The second thing you need is declare an ActivityResultContract.
class MyActivityResultContract : ActivityResultContract<Int, String>() {
override fun createIntent(context: Context, input: Int): Intent {
return Intent(context, ResponseActivity::class.java).apply {
putExtra(EXTRA_INT, input)
}
}
override fun parseResult(resultCode: Int, intent: Intent?): String {
return if (resultCode == Activity.RESULT_OK) {
return intent?.getStringExtra(EXTRA_STRING) ?: "Empty result"
} else {
"Nothing selected"
}
}
}
Finally, you can call the ResponseActivity from your composable using rememberLauncherForActivityResult function like below:
@Composable
fun GetActivityResultScreen() {
var textResult by rememberSaveable { mutableStateOf("") }
val launcher = rememberLauncherForActivityResult(MyActivityResultContract()) { text ->
textResult = text
}
Column {
Button(onClick = {
launcher.launch(Random.nextInt(0, 100))
}) {
Text("Launch Activity")
}
Text(textResult)
}
}
You can find the full source in my repository:
ResponseActivity class and GetActivityResult and MyActivityResultContract composable.