lundi 20 juin 2016

Why does my app crash when I add a second user input to be passed to another activity?

I want to pass multiple user inputs to another activity to be displayed. It works fine when it's just one input but as soon as I am trying to add a second user input to the mix my app keeps crashing. I have been browsing questions for a few days on stackoverflow as well as other forums and have tried multiple approaches but none seem to work for me. Thanks for your help in advance! I am pretty new to all this so apologies if the solution is really simple...

This is the code for my first activity:

public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.simone.code.MESSAGE";
public final static String EXTRA_MESSAGE1 = "com.simone.code.NAME";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

public void sendMessage (View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);

    EditText editText = (EditText) findViewById(R.id.edit_message);
    EditText editName = (EditText) findViewById(R.id.edit_name);

    String message = editText != null ? editText.getText().toString() : null;
    String name = editName != null ? editName.getText().toString() : null;

    intent.putExtra(EXTRA_MESSAGE, message);
    intent.putExtra(EXTRA_MESSAGE1, name);

    startActivity(intent);
}

}

This is the code for my second activity:

public class DisplayMessageActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent intent = getIntent();

    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    String name = intent.getStringExtra(MainActivity.EXTRA_MESSAGE1);

    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(message);

    TextView textView1 = (TextView) findViewById(R.id.name);
    textView1.setText(name);

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
    layout.addView(textView);
    layout.addView(textView1);
}

}

Aucun commentaire:

Enregistrer un commentaire