我抓住了错误信息
“ 5-14 12:39:13.104 2518-2518 / com.example.fdai3744.neueleereapp E / AndroidRuntime:致命例外:主进程:com.example.fdai3744.neueleereapp,PID:2518 java.lang.RuntimeException:无法实例化活动...”
这是我的Java代码
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
@Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}
如果我启动我的应用程序,模拟器将引发错误消息“应用程序已停止”。我应该如何防止该错误?
最佳答案
由...引起
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
在调用setContentView()之前不要分配视图
您修改的代码
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1;
public TextView text1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1 = (Button) findViewById(R.id.button1); //Button
text1 = (TextView)findViewById(R.id.text1); // Textview
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
@Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}