我的应用程序崩溃,因为我声明了一个复选框等于复选框

时间:2015-06-01 20:44:05

标签: java android xml checkbox

当我打开此活动时,我的应用程序崩溃,并说这是由于这行代码所致:

private CheckBox chkWeekly = (CheckBox)findViewById(R.id.alarm_details_repeat_weekly);

alarm_details_repeat_weekly的布局就在这里:

<CheckBox
        android:id="@+id/alarm_details_repeat_weekly"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/alarm_details_label_wednesday"
        android:layout_alignBottom="@+id/alarm_details_label_wednesday"
        android:layout_alignParentRight="true"
        android:checked="true" />

因为有人问,这里是logcat:

         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
        at android.app.Activity.findViewById(Activity.java:2083)
        at minutemovement.mintemovement.com.minutemovement.AlarmDetailsActivity.<init>(AlarmDetailsActivity.java:28)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1572)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1083)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312)

以下是完整代码:http://pastebin.com/EygRhAj4

2 个答案:

答案 0 :(得分:1)

你有一个错字。您在xml中将您的ID声明为alarm_details_repeat_wednesday,但之后尝试获取ID为alarm_details_repeat_weekly的对象。将您的代码更改为:

private CheckBox chkWeekly = (CheckBox)findViewById(R.id.alarm_details_repeat_wednesday);

答案 1 :(得分:0)

尝试删除私有

CheckBox chkWeekly = (CheckBox)findViewById(R.id.alarm_details_repeat_weekly);或在oncreate之外声明私有CheckBox并以这种方式初始化对象:chkWeekly = (CheckBox)findViewById(R.id.alarm_details_repeat_weekly);