211

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?

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
kumareloaded
  • 3,882
  • 14
  • 41
  • 58
  • 2
    read about `startActivityForResult` – Dmitry Zaytsev Jan 12 '13 at 10:30
  • 2
    http://stackoverflow.com/questions/2694947/passing-data-from-new-activity-to-old-activity – Chris Jan 12 '13 at 10:30
  • Another way: `Activity2` puts the value in persistent storage and `Activity1` reads it from there. – Henry Jan 12 '13 at 10:32
  • @kumareloaded: Could you please share the solution here. Pastebin isn't working in my country as of now. – user1903022 Jun 04 '15 at 09:28
  • Possible duplicate of [How to pass the values from one activity to previous activity](http://stackoverflow.com/questions/1124548/how-to-pass-the-values-from-one-activity-to-previous-activity) – andeart Jan 26 '16 at 21:47
  • if I am coming from activity 3 the what will be code... – PankajR May 13 '18 at 14:10
  • Possible duplicate of [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – NoDataDumpNoContribution Apr 25 '19 at 15:51
  • onActivityResult is deprecated use this method https://stackoverflow.com/questions/62671106/onactivityresult-method-is-deprecated-what-is-the-alternative – Ehsan Taghavi Jun 09 '21 at 19:15

8 Answers8

374

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.

dkmann
  • 611
  • 2
  • 8
  • 18
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • 1
    thanks man, if you can could you help me with the similar coding part for SharedPreferences to do the same :) – kumareloaded Jan 12 '13 at 13:58
  • 1
    @kumareloaded : most welcome friend. if you want to do same using `SharedPreferences` then see [this](http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html) example – ρяσѕρєя K Jan 12 '13 at 14:37
  • tired that man had probs doing it but using startActivityForResult it works fine. it will be helpful if you can provide me the code for above scenario using SharedPref :) – kumareloaded Jan 12 '13 at 16:01
  • 2
    @kumareloaded : if you give me code links of both classes with what u have tried using http://pastebin.com/ then i will edit your code – ρяσѕρєя K Jan 12 '13 at 16:03
  • nope bro :( here's my complete code with SharedPref(not working) and startActivityForResult(enclosed as comment which works fine).. http://pastebin.com/gydfWpHN – kumareloaded Jan 12 '13 at 17:41
  • 1
    @kumareloaded : now use [this](http://pastebin.com/MEmU0BKn) code and this will work – ρяσѕρєя K Jan 12 '13 at 17:52
  • 1
    @ρяσѕρєяK: Could you please share the code for above scenario using SharedPref in your answer. Pastebin doesn't open up in many countries. Sharing it here would be of great help, thank you. – user1903022 Jun 04 '15 at 09:27
  • I cant believe! After all these years, i became aware of startActivityForResult for the first time. Thank you so much!!! – ulaserdegor Oct 24 '19 at 12:26
  • que agradable sujeto – Fernando Torres Dec 23 '19 at 01:16
  • by the way, this option was deprecated. so that, you must to use activityResultLauncher to pass data – Michael Fernando Aug 25 '23 at 03:26
33

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);
        }
    }
}
Swayam
  • 16,294
  • 14
  • 64
  • 102
23

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;
        }
    }
}
FindOut_Quran
  • 728
  • 3
  • 10
  • 27
  • Good point. The `onBackPressed()` method is overwritten, so the back function doesn't work. You have to manually call `finish()`. – Gaurav Mall Dec 21 '21 at 19:22
7

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");
} 
katmanco
  • 1,146
  • 12
  • 24
  • This cannot be used for object (only string, boolean, etc) – FindOut_Quran Nov 05 '15 at 03:10
  • 1
    In my case I was launching an activity from a list item in MainActivity and wanted to get user created data back to that list item. startActivityForResult() was not available to me in this case where I was using mContext.startActivity(). @katmanco example here was a helpful work around. – OhNoNotScott Jul 18 '17 at 03:32
  • for my that is a bad election. exist actionForResult – marlonpya Dec 18 '17 at 20:40
3

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...:)

Vishesh Chandra
  • 6,951
  • 6
  • 35
  • 38
3

2021 After the new update in java:

Use activityresultlauncher() instead of startactivityforresult() in the MainActivity.

ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == 123) {
                    Intent data = result.getData();
                    String myStr = data.getStringExtra("MyData");

                    if (!TextUtils.isEmpty(myStr )) {
                        myTextView.setText(myStr);
                    }

                }
            }
        });

Inside onCreate():

myBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Second.class);
            activityResultLaunch.launch(intent);
        }
    });

Inside the SecondActivity (outside onCreate):

@Override
public void onBackPressed() {
    String data = myEditText.getText().toString();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(123, intent);
    finish();
}
Md Anik
  • 61
  • 5
  • `override fun finish() { setResult(RESULT_OK, Intent().apply { putExtra("Parameters", Gson().toJson(result)) }) super.finish() }` We can set the activity result by overriding the finish() function as well. So this method will work even user leave the activity without touching back button... – E. Kolver May 26 '22 at 07:44
  • is it possible to use same like this in Fragment also, because I am luanching Intent from Fragment to activity and try to receive data from Activity to Fragment? – Ninja Jul 19 '22 at 06:29
2

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;

Arash Afsharpour
  • 1,282
  • 11
  • 22
1

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.

Community
  • 1
  • 1
Franci Penov
  • 74,861
  • 18
  • 132
  • 169