您好,我在运行该应用程序时遇到问题,当运行不正常时,它会打开,但是当我按下按钮时,我说该应用程序已停止并且无法运行:“不幸的是,应用程序已停止”。这是我的简单代码,我希望我能尽快得到答案...
谢谢分配:)
package com.stefan.stefan1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView1.setText("Hello Im Stefan !");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
您好,我有一个新问题,我添加了另一个标签(textView2),我试图再次添加此行textView2 =(TextView)findViewById(R.id.textView2);
但是给我在类“ R.java”中添加内容的错误
请帮忙 .. :/
最佳答案
您忘记初始化textView1
。
因此,当您执行以下操作时:
textView1.setText("Hello Im Stefan !");
它会抛出一个
NullPointerException
并停止您的应用程序。如果您在布局中定义了textview,请在
setContentView
之后添加textView1 = (TextView) findViewById(R.id.idOfYourTextView);
附言:出现此类错误时,应始终提供stacktrace(logcat)。
关于android - Android应用错误“不幸的是,应用已停止”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17425481/