1

我的 DatePicker 的声明似乎有问题。空指针在:

pickerDate.init(年, 月, 日, null);

我的代码:

private static DatePicker pickerDate;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        cc = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_reservation);
        Button btn_add = (Button) findViewById(R.id.btn_add_reservation);
        pickerDate = (DatePicker) findViewById(R.id.datePickerId);
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        pickerDate.init(0, 0, 0, null);
//      pickerDate.init(year, month, day, null);
        btn_add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) { open_a_form_page(); } });
    }
}

我的 XML :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="50dp" >

<DatePicker
        android:id="@+id/datePickerId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />


</RelativeLayout>

和错误显示:

08-12 01:06:49.790: E/AndroidRuntime(2410): FATAL EXCEPTION: main
08-12 01:06:49.790: E/AndroidRuntime(2410): java.lang.RuntimeException: Unable to start activity ComponentInfo{xx.xx.cc/ee.rr.name_app.XActivity}: java.lang.NullPointerException

任何想法 ?

4

1 回答 1

3

这似乎是因为您的 Datepicker 与您当前的活动位于不同的 xml 文件中。您要么必须将日期选择器移动到您正在使用的活动的 xml 中,要么膨胀其他文件并从那里获取选择器,如下所示:

View theInflatedView = getLayoutInflater().inflate(R.layout.otherxmlfile, null);
DatePicker pickerDate = (DatePicker) theInflatedView.findViewById(R.id.datePickerId);
于 2013-08-12T01:58:33.433 回答