Lambros
Lambros

Reputation: 151

Android Studio "Unfortunately the Application had to stop" error.

I am trying to pass some variables from one class to another in Android Studio, but my application keeps crashing and I don't know why.

This is the method of the class that executes onClick and calls the other:

 public void sendInfo (View view) {

    Intent intent = new Intent(this, InfoActivity.class);

    EditText editText = (EditText) findViewById(R.id.editText);
    String name = editText.getText().toString();

    EditText editText2 = (EditText) findViewById(R.id.editText2);
    String surname = editText2.getText().toString();

    EditText editText3 = (EditText) findViewById(R.id.editText3);
    String mail = editText3.getText().toString();

    EditText editText4 = (EditText) findViewById(R.id.editText4);
    String age = editText4.getText().toString();


    InfoActivity activity = new InfoActivity();

    activity.displayInfo(name,surname,mail,age);

    startActivity(intent);
}

And this is the method that is being called. It takes the parameters passed and adds them to a TextView:

public void displayInfo(String name, String surname, String mail, String age) {

    TextView textview =  (TextView) findViewById(R.id.textView);

    TextView textview2 = (TextView) findViewById(R.id.textView2);
    TextView textview3 = (TextView) findViewById(R.id.textView3);
    TextView textview4 = (TextView) findViewById(R.id.textView4);

    textview.setText(name.toString());
    textview2.setText(surname.toString());
    textview3.setText(mail.toString());
    textview4.setText(age.toString());


}

Any ideas why the app is crashing? What is wrong?

Upvotes: 0

Views: 386

Answers (1)

reVerse
reVerse

Reputation: 35264

You can't call a method of another Activity before it is created through startActivity(intent).

Furthermore in order to pass values to another Activity you have to use the method Intent putExtra(...). (See here what can be passed)

Example

In your first activity do something like this:

intent.putExtra("KEY_NAME", name);
// TODO other values that need to be passed

In order to retrieve this value in your second activity you have to do something like this (for example in your displayInfo() method):

Bundle bundle = getIntent().getExtras();
textview.setText(bundle.getString("KEY_NAME"));
// TODO get the other values and set the text

Upvotes: 1

Related Questions