receive data from one activity to another automatically

0

I have an activity and a PopUp window that comes up when I click on a button, this window has a button, which detects your click from the class of the window, what the button does is pass some data to the main activity and close the popup with the method finish (); Until then, the problem is that I do not know how to receive the data in the main activity. I need the data (which are Strings) that the popup sends to be received by the main activity (once the popup window is closed) and they are passed to a TextView of that activity, all automatically.

PS: When I do the Intent on the PopClick onClick, I do not use the startActivity (intent); because in that way the main activity is restarted, which is why I only give it finish (); PopUp and it closes.

OnClick of the PopUp button:

public void guardar2(View view){
    Intent intent= new Intent (this, Activity1.class);
    intent.putExtra("asunto",edit_asunto.getText());
    intent.putExtra("usuario",edit_usuario.getText());
    intent.putExtra("contra",edit_contra.getText());
    intent.putExtra("id",ID);
    finish();
}

I do not know what method to use for Activity1 to receive the data and store it in a TextView (All automatically without needing to touch another button).

    
asked by Valen W. 23.08.2018 в 00:48
source

1 answer

0

In Activity1 we get the extras and assign them to the text, for that, we must first get the intent that launched that activity to get the extras that you pass from MainActivity.

Intent intent = getIntent();

and then you only get the values

String asunto = intent.getStringExtra("asunto");
String usuario = intent.getStringExtra("usuario");
String contra = intent.getStringExtra("contra");
String id = intent.getStringExtra("id");

and we assign it to some textView

txtView.setText(asunto);
txtView2.setText(usuario);
txtView3.setText(contra);
txtView4.setText(id);

To do it with good practice, you can check that the extras are different from null so that you do not have a NullPointerException if the values that are happening do not exist.

In Activity1

Bundle extras = getIntent().getExtras(); 
String asunto,usuario,contra,id;

if (extras != null) {
    asunto = extras.getString("asunto");
    usuario = extras.getString("usuario");
    contra = extras.getString("contra"); 
    id = extras.getString("id");
}

then you assign it the same

    txtView.setText(asunto);
    txtView2.setText(usuario);
    txtView3.setText(contra);
    txtView4.setText(id);

Either serves, but I recommend using the last option to check for possible null

    
answered by 23.08.2018 в 01:50