Send data between activities

5

I have a problem. I have 2 activities, the main one and a second screen. I want the 2nd screen to send data to the main screen but when I start the application it tells me that it stopped and it closes. When I do it the other way around (From the main page to the 2nd screen) it works without problems.

Does anyone know why the error? To pass the data I'm using Bundle, is it the correct way or is there a better one?

Thank you.

Main screen:

public class MainActivity extends AppCompatActivity {

TextView tv2;
Button b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv2=(TextView)findViewById(R.id.tv2);
    b2=(Button)findViewById(R.id.b2); 

    Bundle parametros = this.getIntent().getExtras();
    String datos = parametros.getString("datos"); 
    tv2.setText(datos);
}

public void segunda_pantalla(View view){
    Intent i=new Intent(this, segunda_pantalla.class);
    startActivity(i);
}

Second Screen:

public class pantalla2 extends AppCompatActivity {

Button b1;
TextView tv1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pantalla2);

    b1=(Button)findViewById(R.id.b1);
    tv1=(TextView)findViewById(R.id.tv1);
}

public void b1(View view){

    tv1.setText("1");

    String datos = tv1.getText().toString();

    Bundle parmetros = new Bundle();
    parmetros.putString("datos", datos);

    Intent i = new Intent(this, MainActivity.class);
    i.putExtras(parmetros);
    startActivity(i);
}
    
asked by Agustin Val 30.11.2016 в 19:14
source

4 answers

6

How to send data between Activities.

To send the data is generally done by a Bundle in which values can be added and that bundle is sent through a Intent . You can specify the sending of any type of element or element array by specifying the name:

    intent.putExtra("usuario", "StackOverflow!");
    intent.putExtra("id", 123);
    intent.putExtra("myByte", 0xa);
    intent.putExtra("latitud", 0.12324234);
    startActivity(intent);      

The values are obtained in the Activity that the Bundle receives via getExtras () or the specific method for getting data type received . Return null if you can not find value.

String valor = getIntent().getExtras().getString("usuario");

or simply:

String valor = getIntent().getStringExtra("usuario");

Your problem happens because when you start MainActivity you try to receive a bundle which has value null , you can verify it in the LogCat.

  

Caused by: java.lang.NullPointerException
  at MainActivity.onCreate (MainActivity.java)

Perform the following validation:

 Bundle parametros = this.getIntent().getExtras();
 if(parametros !=null){
    String datos = parametros.getString("datos"); 
   tv2.setText(datos);
 } 

Take into account that in the activity that you do not ensure you receive a Bundle , you have to perform this validation.

It is also important to comment that to return to the first Activity you do not need to do it by means of a Intent , simply use finish() to close it.

Other similar questions on the site that would be of great help to you:

answered by 30.11.2016 / 20:50
source
2

In the first activity you have to check that your variable paremetros is not null

Bundle parametros = this.getIntent().getExtras();

Try something like this

 Bundle parametros = this.getIntent().getExtras();
 if(parametros != null) {  
 String datos = parametros.getString("datos"); 
 tv2.setText(datos);}
    
answered by 30.11.2016 в 19:54
2

That is not the correct way to receive the data, there is a method called startActivityForResult() :

public void segunda_pantalla(View view){
    Intent i=new Intent(this, segunda_pantalla.class);
    startActivityForResult(i, 1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) { // el "1" es el numero que pasaste como parametro
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("datos");
            // tu codigo para continuar procesando
            tv2.setText(datos);
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            // código si no hay resultado
        }
    }
}//onActivityResult

and to return data from the second activity:

public void b1(View view){
    tv1.setText("1");

    String datos = tv1.getText().toString();

    //Bundle parmetros = new Bundle();
    //parmetros.putString("datos", datos);
    //Intent i = new Intent(this, MainActivity.class);
    //i.putExtras(parmetros);
    //startActivity(i);

    Intent returnIntent = new Intent();
    returnIntent.putExtra("datos",datos);
    setResult(Activity.RESULT_OK,returnIntent);
    finish();
}

And the application stops because when you run the app the first time you are requesting data in onCreate() but there is no such data:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv2=(TextView)findViewById(R.id.tv2);
    b2=(Button)findViewById(R.id.b2); 

    //Bundle parametros = this.getIntent().getExtras();
    //String datos = parametros.getString("datos"); 
    //tv2.setText(datos);
}

Here is a bit of the Official StartActivity Documentation () and StartActivityForResult ()

Note The finish() function should be used almost compulsorily, otherwise when you enter the second activity and return to the first activity you will be cycling between activities, this can be proven when you press the back button will return you to the second activity, then to the first and at the end you will leave the application.

Fun fact : If you check the Activities life cycle you will notice that when a second activity is executed the current activity is put in onPause() therefore when you return to the main activity the method onResume() instead of onCreate() is executed. (There are only some tips to optimize your code)

    
answered by 30.11.2016 в 19:23
1

I would do it in the following way Activity 2

Intent i = new Intent(this, MainActivity.class);
i.putExtras("datos", datos);
startActivity(i);

And I receive it in MainActivity

Intent recibir = getIntent();
String datos = recibir.getStringExtra("datos");

Ready, you have them

    
answered by 30.11.2016 в 19:39