我试图在 Android Studio 中将一些变量从一个类传递到另一个类,但我的应用程序不断崩溃,我不知道为什么。
这是执行onClick并调用其他类的方法:
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);
}
这就是正在被调用的方法。它获取传递的参数并将它们添加到 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());
}
您知道应用程序崩溃的原因吗?怎么了?
最佳答案
在通过 startActivity(intent)
创建另一个 Activity
之前,您不能调用它的方法。
此外,为了将值传递给另一个 Activity,您必须使用方法 Intent putExtra(...)
。 (参见here可以传递什么)
示例
在您的第一个 Activity 中执行如下操作:
intent.putExtra("KEY_NAME", name);
// TODO other values that need to be passed
为了在您的第二个 Activity 中检索此值,您必须执行类似的操作(例如在您的 displayInfo()
方法中):
Bundle bundle = getIntent().getExtras();
textview.setText(bundle.getString("KEY_NAME"));
// TODO get the other values and set the text
关于java - Android Studio "Unfortunately the Application had to stop"错误。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25959542/