kumareloaded kumareloaded -4 years ago 84
Android Question

How to pass data from 2nd activity to 1st activity when pressed back? - android

I've 2 activities, Activity1 and Activity2.

In

Activity1
I've a Button and TextView.
When the button is clicked Activity2 is started.

In
Activity2
I've an EditText.

I want to display the data retrieved from EditText in Activity2 in the TextView in Activity1 when back is pressed from Activity2.

can someone help me with the code to make this work?

Answer Source

Start your Second Activity as startActivityForResult and use setResult() method for sending data back from Activity2 to Activity1. In activity1 you will need to Override onActivityResult for Updating TextView with EditText data from Activity2

for example:

Start Activity2 from Acivity1 as:

Intent i = new Intent(this,  Activity2.class);
startActivityForResult(i, 1);

in Activity2 use setResult for sending data back :

Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here")
setResult(RESULT_OK, intent);        
finish();

and in First Activity receive data as onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK){
             String stredittext=data.getStringExtra("edittextvalue");
         }     
    }
} 

and if you can use SharedPreferences also for Sharing data Between Activities

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download