1

I have activity_main and second_activity. I have a button on activity_main that opens second_activity in a dialog. How can I create three textEdit's with a button in second_activity and display the result when user submits on main_activity? This Sending data back to the Main Activity in android kind of solved my question. It shows the first field's data on SecondActivity in all 3 textViews on MainActivity.

My current sample app code on SecondActivity

@Override
public void onClick(View view) {
            EditText editText = (EditText)findViewById
            (R.id.etUsername);
            String stringToPassBack = editText.getText().toString();
            // put the string to pass back into an Intent and close 
            this activity
            Intent intent = new Intent();
            intent.putExtra("@string/send", stringToPassBack);
            setResult(RESULT_OK, intent);
            finish();
        }

How do I add the other 2 fields; etPassword and etEmail

  • user inputs text in edit text in SecondActivity. but you want that to display in MainActivity? – letsCode Aug 15 '17 at 18:52
  • Yes. I have tried a few tutorials on net but nothing seems to work. – S. Taljaard Aug 15 '17 at 19:03
  • Read this https://stackoverflow.com/questions/920306/sending-data-back-to-the-main-activity-in-android. 1. Start the second activity with startActivityForResult. 2. Save the texts from the EditTexts into an intent, call setResult(Activity.RESULT_OK, intent) and finish the activity. 3. Receive the result in your first activity in onActivityResult (the passed intent is holding the data). – Jason Saruulo Aug 15 '17 at 19:08
  • Possible duplicate of [Sending data back to the Main Activity in android](https://stackoverflow.com/questions/920306/sending-data-back-to-the-main-activity-in-android) – Jason Saruulo Aug 15 '17 at 19:11
  • Thanks. I looked at those links, and the information helped. I have three fields; username, password and email. (this is sample) The code on the links only helps with 1 field, I am struggling to get the other fields to work. It shows the first filed's data in all 3 textViews on MainActivity. – S. Taljaard Aug 16 '17 at 18:04

1 Answers1

0

In the MainActivity start SecondActivity with startActivityForResult() instead of startActivity:

startActivityForResult(intent, YOUR_REQUEST_CODE);

In second activity, when you want to close activity and come back to MainActivity, use this code:

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

And again in MainActivity add a callback method onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == YOUR_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Your result is in data intent's extras
        }
    }
}
Ali Behzadian Nejad
  • 8,804
  • 8
  • 56
  • 106