0

I understand how to pass data from the current activity to the second activity using intent.putExtra.

These posts explain it very well: activity to activity callback listener

How do I pass data between Activities in Android application?

However what I'm interested in is that the second activity will send data back to the first activity that opened it.

Say, MeetActivity is my main activity, and then I activate EditProfileActivity which is the secondary activity:

override fun startEditProfile() {
    startActivity(EditProfileActivity.newIntent(this))
    overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_down)
}

In the EditProfileActivity I created a companion object:

companion object {
    fun newIntent (context: Context?) = Intent(context, EditProfileActivity::class.java)
}

Still I don't understand how MeetActivity which is the main activity, can receive back information from EditProfileActivity (second activity) Thanks in advance

sir-haver
  • 3,096
  • 7
  • 41
  • 85

1 Answers1

2

You should use startActivityForResult()

From Docs

Starting another activity doesn't have to be one-way. You can also start another activity and receive a result back. To receive a result, call startActivityForResult() (instead of startActivity()).

You can start an activity for result as follows

const val PICK_CONTACT_REQUEST = 1 // The request code.
// ...
private fun pickContact() {
    val pickContactIntent = Intent(Intent.ACTION_PICK).apply {
        // Show user only the contacts that include phone numbers.
        setDataAndType(
            Uri.parse("content://contacts"),
            Phone.CONTENT_TYPE
        )
    }

    startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST)
}

And to receive the result override the following method

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == Activity.RESULT_OK) {
            // The user picked a contact.
            // The Intent's data Uri identifies which contact was selected.

            // Do something with the contact here (bigger example below)
        }
    }
}
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46