androidandroid-activityparent-childpass-data

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?


Solution

  • Start Activity2 with 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:

    In Activity1, start Activity2 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 Activity1, receive data with 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");
             }     
        }
    } 
    

    If you can, also use SharedPreferences for sharing data between Activities.