应用程序崩溃,我收到此错误:
02-19 13:48:34.168: E/AndroidRuntime(1070): FATAL EXCEPTION: main
02-19 13:48:34.168: E/AndroidRuntime(1070): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.prva/com.example.prva.MainMenu}: java.lang.NullPointerException
02-19 13:48:34.168: E/AndroidRuntime(1070): Caused by: java.lang.NullPointerException
02-19 13:48:34.168: E/AndroidRuntime(1070): at com.example.prva.MainMenu.onCreate(MainMenu.java:49)
当我尝试运行此活动时:
public class MainMenu extends Activity{
Calendar c = Calendar.getInstance();
int currentsecond = c.get(Calendar.SECOND);
Handler h=new Handler();
DatabaseManager db;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
h.post(new Runnable(){
@Override
public void run() {
String currentDateTimeString = new SimpleDateFormat("dd.MM.yyyy HH:mm").format(new Date());
TextView text = (TextView) findViewById(R.id.txtDate);
text.setText(currentDateTimeString);
h.postDelayed(this, 60000);
}
});
db = new DatabaseManager(this);
Button btnalarm = (Button) findViewById(R.id.btnSetAlarm);
btnalarm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainMenu.this, SetAlarm.class));
}
});
Button btnmelody = (Button)findViewById(R.id.btnSetMelody);
btnmelody.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainMenu.this, SetMelody.class));
}
});
Button btnlist = (Button) findViewById(R.id.btnAlarmList);
btnlist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent1 = new Intent(MainMenu.this, AlarmList.class);
startActivity(intent1);
}
});
Button btndata = (Button) findViewById(R.id.btnDatabase);
btndata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(MainMenu.this, ManageDatabase.class);
startActivity(intent2);
}
});
}
}
第49行是:
btnalarm.setOnClickListener(new View.OnClickListener() {
答案 0 :(得分:3)
当你写这篇文章时:
Button btnalarm = (Button) findViewById(R.id.btnSetAlarm);
btnalarm.setOnClickListener(new View.OnClickListener() {
你假设发现该视图会返回一个非空按钮,但你错了。
查看搜索失败的原因,您将获得答案。
答案 1 :(得分:1)
当您尝试findViewById
Button
时,问题应该是这个问题,看一下这个ID(R.id.btnSetAlarm
)在您的布局中是否相同,或者此按钮位于setContentView(R.layout.activity_main);
答案 2 :(得分:1)
试试这个:
btnalarm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO do your stuff here
}
});
并确保您的“ btnSetAlarm ”在您的声明* main_activity.xml *