Skip to content Skip to sidebar Skip to footer

How Do I Pass Data Between Activities When I Press Back Button In Android?

I'm trying to send data between activities using: on Activity 2 Bundle bloc = new Bundle(); bloc.putString('DataLoc', et1.getText().toString()); Intent intent = new Intent(this, Ac

Solution 1:

How do I pass data between activities when I press back button in Android?

Start second Activity using StartActivityForResult and use onActivityResult in parent Activity for updating TextView using received from second Activity

In Second Activity override onBackPressed() method and call setResult for send data using Intent:

@OverridepublicvoidonBackPressed() {
        Intentdata=newIntent();
        // add data to Intent 
        setResult(Activity.RESULT_OK, data);
       super.onBackPressed();
}

Solution 2:

You can use onActivityResult();

For Sending

Intent in= newIntent();

setResult(Activity.RESULT_OK, in);
finish();

For Recieving

@OverridepublicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch(requestCode) {
    case (abc) : {
      if (resultCode == Activity.RESULT_OK) {
      // your stuff
      }
      break;
    } 
  }

}

Solution 3:

I think you are looking for an startActivityForResult() and onActivityResult() methods. Here you can find an example how to use it.

Solution 4:

Use 'DataLoc' string to get back the required value in the activity. You must use startActivityForResult() and onActivityResult() methods and get the value back using setResult() method.

Post a Comment for "How Do I Pass Data Between Activities When I Press Back Button In Android?"