[android] 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?

This question is related to android android-activity parent-child pass-data

The answer is


Other answers were not working when I put setResult in onBackPressed. Commenting call to super onBackPressed and calling finish manually solves the problem:

@Override
public void onBackPressed() {
    //super.onBackPressed();
    Intent i = new Intent();
    i.putExtra(EXTRA_NON_DOWNLOADED_PAGES, notDownloaded);
    setResult(RESULT_OK, i);
    finish();
}

And in first activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == QUEUE_MSG) {
        if (resultCode == RESULT_OK) {
            Serializable tmp = data.getSerializableExtra(MainActivity.EXTRA_NON_DOWNLOADED_PAGES);
            if (tmp != null)
                serializable = tmp;
        }
    }
}

and I Have an issue which I wanted to do this sending data type in a Soft Button which I'd made and the softKey which is the default in every Android Device, so I've done this, first I've made an Intent in my "A" Activity:

            Intent intent = new Intent();
            intent.setClass(context, _AddNewEmployee.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, 6969);
            setResult(60);

Then in my second Activity, I've declared a Field in my "B" Activity:

private static int resultCode = 40;

then after I made my request successfully or whenever I wanted to tell the "A" Activity that this job is successfully done here change the value of resultCode to the same I've said in "A" Activity which in my case is "60" and then:

private void backToSearchActivityAndRequest() {
    Intent data = new Intent();
    data.putExtra("PhoneNumber", employeePhoneNumber);
    setResult(resultCode, data);
    finish();
}

@Override
public void onBackPressed() {
    backToSearchActivityAndRequest();
}

PS: Remember to remove the Super from the onBackPressed Method if you want this to work properly.

then I should call the onActivityResult Method in my "A" Activity as well:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6969 && resultCode == 60) {
            if (data != null) {
                    user_mobile = data.getStringExtra("PhoneNumber");
                    numberTextField.setText(user_mobile);
                    getEmployeeByNumber();
            }
        }
    }

that's it, hope it helps you out. #HappyCoding;


TL;DR Use Activity.startActivityForResult

Long answer:

You should start by reading the Android developer documentation. Specifically the topic of your question is covered in the Starting Activities and Getting Results section of the Activity documentation.

As for example code, the Android SDK provides good examples. Also, other answers here give you short snippets of sample code to use.

However, if you are looking for alternatives, read this SO question. This is a good discussion on how to use startActivityForResults with fragments, as well as couple othe approaches for passing data between activities.


Read these:

  1. Return result to onActivityResult()
  2. Fetching Result from a called activity - Android Tutorial for Beginners

These articles will help you understand how to pass data between two activities in Android.


Take This as an alternate to startActivityforResult.But keep in mind that for such cases this approach can be expensive in terms of performance but in some cases you might need to use.

In Activity2,

@Override
public void onBackPressed() {
String data = mEditText.getText();
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
Editor editor = sp.edit();
editor.putString("email",data);
editor.commit();
}

In Activity1,

 @Override
public void onResume() {
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
String  dataFromOtherAct= sp.getString("email", "no email");
} 

From your FirstActivity call the SecondActivity using startActivityForResult() method.

For example:

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

In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

For example: In secondActivity if you want to send back data:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don't want to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

Now in your FirstActivity class write following code for the onActivityResult() method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

this is your first Activity1.

public class Activity1 extends Activity{
private int mRequestCode = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(this, Activity2.class);
    startActivityForResult(intent, mRequestCode);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == mRequestCode && resultCode == RESULT_OK){
        String editTextString = data.getStringExtra("editText");
    }
}
}

From here you are starting your Activity2.class by using startActivityForResult(mRequestCode, Activity2.class);

Now this is your second Activity, name is Activity2

public class Activity2 extends Activity {
private EditText mEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //mEditText = (EditText)findViewById(R.id.edit_text);

    Intent intent = new Intent();
    intent.putExtra("editText", mEditText.getText().toString());
    setResult(RESULT_OK, intent);
}

}

Now when you done with your second Activity then you call setResult() method, from onBackPress() or from any button click when your Activity2 will destroy then your Activity1's call back method onActivityResult() will call from there you can get your data from intent..

Hope it will help to you...:)


Activity1 should start Activity2 with startActivityForResult().

Activity2 should use setResult() to send data back to Activity1.

In Activity2,

@Override
public void onBackPressed() {
    String data = mEditText.getText();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(resultcode, intent);
}

In Activity1,

onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String myStr=data.getStringExtra("MyData");
            mTextView.setText(myStr);
        }
    }
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to parent-child

The specified child already has a parent. You must call removeView() on the child's parent first (Android) Example of waitpid() in use? get parent's view from a layout CSS :: child set to change color on parent hover, but changes also when hovered itself How to pass data from 2nd activity to 1st activity when pressed back? - android Make absolute positioned div expand parent div height JavaScript DOM: Find Element Index In Container How to set opacity in parent div and not affect in child div? How to select <td> of the <table> with javascript? Maven: Non-resolvable parent POM

Examples related to pass-data

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