Help, activity closes when launched

3

I'm new and I'm starting with Android in Android Studio .. I have a simple application that has two activities, the 1st asks for and sends a name and the second shows it, but when the second one is launched it does not show the name, the application is closed without showing the name ..

Main Activity

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

private EditText txtNombre;
private Button btnAceptar;

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

    //Obtenemos una referencia a los controles de la interfaz
    txtNombre = (EditText)findViewById(R.id.txtNombre);
    btnAceptar = (Button)findViewById(R.id.btnAceptar);

    //Implementamos el evento click del botón
    btnAceptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Creamos el Intent
            Intent intent =
                    new Intent(MainActivity.this, SaludoActivity.class);

            //Creamos la información a pasar entre actividades
            Bundle b = new Bundle();
            b.putString("NOMBRE", txtNombre.getText().toString());

            //Añadimos la información al intent
            intent.putExtras(b);

            //Iniciamos la nueva actividad
            startActivity(intent);


     }
        });
    }
}

Actity greeting (2nd activity)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class SaludoActivity extends AppCompatActivity {

private TextView txtSaludo;

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

    //Localizar los controles
    txtSaludo = (TextView)findViewById(R.id.txtSaludo);

    //Recuperamos la información pasada en el intent
    Bundle bundle = this.getIntent().getExtras();

    //Construimos el mensaje a mostrar
    txtSaludo.setText("Hola " + bundle.getString("NOMBRE"));
}
}

What can I do so that the app does not close when I press the OK button? .. To test the app I am using bluestack, I do not know if it will have something to do .. Thanks!

    
asked by EnzzoG 06.06.2016 в 04:48
source

2 answers

1

You must always add the Logcat to define the problem, since there may be several causes for your application to close.

I notice that your code is correct, the first thing is to ensure your Activity GreetingActivity, this registered in your AndroidManifest.xml

<activity android:name="SaludoActivity" />

Although the code is correct when reading the bundle in the second activity another detail that could close your application is that the value of "NAME" could be null, I recommend adding this validation:

 //Recuperamos la información pasada en el intent
    Bundle bundle = this.getIntent().getExtras();

if(bundle.getString("NOMBRE") != null){
    //Construimos el mensaje a mostrar
    txtSaludo.setText("Hola " + bundle.getString("NOMBRE"));
}
    
answered by 06.06.2016 в 05:10
0

I see you're using Bundle and this is for fragments, with the intent is enough: use this

Intent intent = new Intent(MainActivity.this, SaludoActivity.class);
//Creamos la información a pasar entre actividades
intent.putExtra("NOMBRE", txtNombre.getText().toString());
//Iniciamos la nueva actividad
startActivity(intent);

Actity greeting (2nd activity)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saludo);
    final int nombre = getIntent().getIntExtra("NOMBRE", 0);
        Intent intent = getIntent();
        String nombreExtra = "";
      // Validar que este llegando 
        if (intent != null && intent.hasExtra("NOMBRE")) {
       //  get del parametro 
            nombreExtra = intent.getStringExtra("NOMBRE");
        }

    //Construimos el mensaje a mostrar
    txtSaludo.setText("Hola " + nombreExtra);
}
}

PS: we can improve your code based on this: 1. as NAME is a costante creates a static and immutable contact for this, 2. Also to respect the principle of Single Resposability let the put Extra within activity private static final String EXTRA_NAME="NAME";

Then your two Activity will be left like this:

public class SaludoActivity extends AppCompatActivity {

private static final String EXTRA_NAME = "NOMBRE";
private TextView txtSaludo;

public static Intent getStartSaludoActivityIntent(@NonNull Activity activity, String nombre) {
        Intent intent = new Intent(activity, SaludoActivity.class);
        intent.putExtra(EXTRA_NAME, nombre);
        return intent;
    }


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saludo);
    //Localizar los controles
    txtSaludo = (TextView)findViewById(R.id.txtSaludo);

final int nombre = getIntent().getIntExtra("NOMBRE", 0);
            Intent intent = getIntent();
            String nombreExtra = "";
          // Validar que este llegando 
            if (intent != null && intent.hasExtra(EXTRA_NAME)) {
           //  get del parametro 
                nombreExtra = intent.getStringExtra(EXTRA_NAME);
            }

        //Construimos el mensaje a mostrar
        txtSaludo.setText("Hola " + nombreExtra);   
}
}

and from your Main activity you call the static method

public class MainActivity extends AppCompatActivity {

private EditText txtNombre;
private Button btnAceptar;

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

    //Obtenemos una referencia a los controles de la interfaz
    txtNombre = (EditText)findViewById(R.id.txtNombre);
    btnAceptar = (Button)findViewById(R.id.btnAceptar);

    //Implementamos el evento click del botón
    btnAceptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Iniciamos la nueva actividad
        startActivity(SaludoActivity.getStartSaludoActivityIntent(MainActivity.this, txtNombre.getText().toString()));


     }
        });
    }
}
    
answered by 18.06.2018 в 18:08