How to return Activity call data to the one who called it?

Asked

Viewed 1,800 times

5

I saw several examples of passing data between Activity of a Textview receiving data from a Edittext. Which is the best way to do the reverse, I explain:

I have a reader that reads a barcode and shows the result in a Textview I would like, when closing this screen, the one that opened it receive this result in a Edittext to record it in the bank.

2 answers

6


The mechanism used to receive values from a Activity after it is abandoned is, by evoking it, to use startActivityForResult() instead of startActivity().

At first Activity:

static final int ACTIVITY_2_REQUEST = 1;

Intent i = new Intent(this, SegundaActivity.class);
startActivityForResult(i, ACTIVITY_2_REQUEST);

In the second Activity:

//Quando tiver o resultado pronto para ser devolvido à primeira activity

String resultado = seuTextView.getText().toString();
Intent returnIntent = new Intent();
returnIntent.putExtra("resultado",resultado);
setResult(RESULT_OK,returnIntent);

To receive the value do the override of the method onActivityResult() at first Activity:

@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == ACTIVITY_2_REQUEST) {
        if(resultCode == RESULT_OK){
            String resultado = data.getStringExtra("resultado");
            //Coloque no EditText
            seuEditText.setText(resultado);
        }
    }
}

1

I prefer to work on Android using Parcelable, which greatly facilitates the passage of objects of any kind between Activitys, in addition to having much faster return, better processing.

EX:

// ENVIO
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("nome", "Joao");


//RECEBENDO

Intent intent = getIntent();
String nome = intent.getStringExtra("nome");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.