Activity results let one screen send data back to the screen that started it. This helps apps share information between screens easily.
Activity results in Android Kotlin
val getResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
// Use the returned data here
}
}
// To start the activity
val intent = Intent(this, OtherActivity::class.java)
getResult.launch(intent)This uses registerForActivityResult to handle results in a modern way.
Always check resultCode to know if the result is OK or cancelled.
InputActivity and expects a string extra named "text" back.val getResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val returnedText = result.data?.getStringExtra("text")
// Use returnedText
}
}
val intent = Intent(this, InputActivity::class.java)
getResult.launch(intent)val getImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) {
// Use the image Uri
}
}
getImage.launch("image/*")This app has two screens. The first screen has a button that opens the second screen. The second screen has a button that sends back a message to the first screen. The first screen shows the message in a TextView.
class MainActivity : AppCompatActivity() { private lateinit var resultLauncher: ActivityResultLauncher<Intent> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val returnedData = result.data?.getStringExtra("message") findViewById<TextView>(R.id.textView).text = returnedData ?: "No message" } } findViewById<Button>(R.id.button).setOnClickListener { val intent = Intent(this, SecondActivity::class.java) resultLauncher.launch(intent) } } } class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) findViewById<Button>(R.id.returnButton).setOnClickListener { val resultIntent = Intent().apply { putExtra("message", "Hello from SecondActivity") } setResult(Activity.RESULT_OK, resultIntent) finish() } } }
Use registerForActivityResult instead of the old startActivityForResult method.
Always check if the returned data is null before using it to avoid crashes.
Remember to call setResult and finish() in the second activity to send data back.
Activity results let one screen send data back to the screen that started it.
Use registerForActivityResult to handle results safely and simply.
Always check the result code and returned data before using it.
Practice
registerForActivityResult in Android Kotlin?Solution
Step 1: Understand the role of
This function is designed to handle results from activities started for a result safely and simply.registerForActivityResultStep 2: Compare with other options
Starting an activity without expecting a result or registering broadcast receivers are unrelated to this function.Final Answer:
To safely receive data back from another activity -> Option DQuick Check:
Activity result handling = A [OK]
- Confusing it with starting activities without results
- Thinking it registers broadcast receivers
- Assuming it creates fragments
Solution
Step 1: Identify the correct function name
The correct function isregisterForActivityResult, not any shortened or altered form.Step 2: Check the contract and lambda syntax
The contractActivityResultContracts.StartActivityForResult()and lambda parameter{ result -> }are correctly used in val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> /* handle result */ }.Final Answer:
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> /* handle result */ } -> Option AQuick Check:
Correct function name and syntax = B [OK]
- Using incorrect function names like registerActivityResult
- Omitting parentheses in contract instantiation
- Wrong lambda syntax
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val name = result.data?.getStringExtra("username")
println(name)
} else {
println("No data")
}
}Solution
Step 1: Check the result code condition
The code checks ifresult.resultCode == Activity.RESULT_OK, which is true in this case.Step 2: Extract the "username" from intent data
The intent data contains key "username" with value "Alice", sonamewill be "Alice" and printed.Final Answer:
Alice -> Option BQuick Check:
Result OK with data returns value = D [OK]
- Ignoring resultCode and printing 'No data'
- Assuming data is null without checking
- Not using safe call operator on intent data
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val name = result.data!!.getStringExtra("username")
if (result.resultCode == Activity.RESULT_OK) {
println(name)
}
}Solution
Step 1: Analyze the order of operations
The code force unwrapsresult.data!!before checking ifresult.resultCode == Activity.RESULT_OK.Step 2: Understand potential crash
If the result is not OK or data is null, force unwrapping causes a crash. The check should come before accessing data.Final Answer:
Unsafe call on result.data before checking resultCode -> Option AQuick Check:
Check resultCode before accessing data = A [OK]
- Force unwrapping nullable data without checks
- Accessing data before verifying resultCode
- Ignoring null safety in Kotlin
registerForActivityResult to achieve this?Solution
Step 1: Identify the correct contract for picking a contact
ActivityResultContracts.PickContact()is designed to pick a contact and return its URI.Step 2: Check the lambda parameter and usage
The lambda receives a URI nullable parameter, which is safely checked before printing.Step 3: Eliminate other options
val pickContact = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> println(result.data?.getData().toString()) } uses a generic contract but does not check resultCode; A and D are unrelated contracts for permissions and taking pictures.Final Answer:
val pickContact = registerForActivityResult(ActivityResultContracts.PickContact()) { uri -> if (uri != null) println(uri.toString()) } -> Option CQuick Check:
Use PickContact contract for contact URI = C [OK]
- Using StartActivityForResult without checking resultCode
- Confusing permission or picture contracts with contact picking
- Not handling nullable URI safely
Ready to prove it?
Pass the test and this pattern moves unknown
