How to pass data through an Intent to Main Activity?

Asked

Viewed 215 times

0

I’m developing a small android app to exercise what I’ve already learned. The application consists of two Activity’s, Mainactivity and a second Activity. On Main I have a textView and a button, while in the second Activity I have an editText and two buttons, for confirmation and cancellation. The operation of the application should occur as follows: when pressing the button in the Main Activity an Intent takes us to the second Activity, and we must enter some text in editText and press the confirm button, going again to Mainactivity, where the textView will have the previously typed value.

The problem is that I don’t know how to pass the typed data to Main. I believe it is something simple but I don’t have many ideas on how to look. I’d like at least one north to guide me.

Thanks in advance.

  • I found the resolution here: https://stackoverflow.com/questions/14292398/how-to-pass-data-from-2nd-activity-to-1st-activity-when-pressed-back-android using startActivityForResult

1 answer

1

This is very simple. From what I understand Oce already has the logic of the program and just wants to pass information from one Activity to another, so follow the steps.

In the Activity which has the + text button, etc. Put this on onClick of your Button:

Create a new Intent:

Intent intent = new Intent(ActivityAtual.this, SegundaActivity.class);

Where this second Activity.class you fill with the name of Activity to which the button will redirect.

//To send information to another Activity

intent.putExtra("nomeConteudo", "Conteudo de texto que queira enviar");

//Redirect to another Activity

startActivity(intent);

To receive information from Previous Activity:

String valorRecebido;
Bundle extras = getIntent().getExtras();
if(extras != null) {
 valorRecebido = extras.getString("nomeConteudo");
}

//If you want to insert in a Textview

textview.setText(valorRecebido);
  • I tested this way however always received an error from Nullpointer. I believe this was because the first time she ran Activity Main, no information was passed on to her. To solve this problem it is necessary to use, in Activity Main, the startActivityForResult method.

Browser other questions tagged

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