How to pass the values from one activity to previous activity

Viewed 97820

How do I pass a value from one screen to its previous screen?

Consider this case: I have two activities. The first screen has one TextView and a button and the second activity has one EditText and a button.

If I click the first button then it has to move to second activity and here user has to type something in the text box. If he presses the button from the second screen then the values from the text box should move to the first activity and that should be displayed in the first activity TextView.

6 Answers

To capture actions performed on one Activity within another requires three steps.

Launch the secondary Activity (your 'Edit Text' Activity) as a subactivity by using startActivityForResult from your main Activity.

Intent i = new Intent(this,TextEntryActivity.class);    
startActivityForResult(i, STATIC_INTEGER_VALUE);

Within the subactivity, rather than just closing the Activity when a user clicks the button, you need to create a new Intent and include the entered text value in its extras bundle. To pass it back to the parent call setResult before calling finish to close the secondary Activity.

Intent resultIntent = new Intent();
resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, enteredTextValue);
setResult(Activity.RESULT_OK, resultIntent);
finish();

The final step is in the calling Activity: Override onActivityResult to listen for callbacks from the text entry Activity. Get the extra from the returned Intent to get the text value you should be displaying.

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) {     
  super.onActivityResult(requestCode, resultCode, data); 
  switch(requestCode) { 
    case (STATIC_INTEGER_VALUE) : { 
      if (resultCode == Activity.RESULT_OK) { 
      String newText = data.getStringExtra(PUBLIC_STATIC_STRING_IDENTIFIER);
      // TODO Update your TextView.
      } 
      break; 
    } 
  } 
} 

The best way to do here is to put variable to a common class which is defined outside the scope

public class Utils 
{
    public static String mPosition;
}

inside your code (e.g. OnButtonClick etc...)

Intent intent = new Intent(Intent.ACTION_PICK, 
ContactsContract.Contacts.CONTENT_URI);
Utils.mPosition = mViewData.mPosition + "";
LogHelper.e(TAG, "before intent: " + Utils.mPosition);
startActivityForResult(intent, Keys.PICK_CONTACT);

inside the code of

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Keys.PICK_CONTACT) { if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData();

            //you may use the variable here after intent result
            LogHelper.e(TAG, "after intent: " + Utils.mPosition);
....
Related