简体   繁体   中英

Android Studio - DatePicker in AlertDialog, null object reference

I have an activity in my app, where I want the user to pick the date from a DatePicker, which is contained in an AlertDialog. In the AlertDialog, I have set a view, to an xml layout file (, which contains only a LinearLayout, with a single DatePicker.

The code is really simple, and looks like this, just below onCreate().

AlertDialog.Builder alert  = new AlertDialog.Builder(this);
alert.setView(R.layout.activity_alertdialog_date);
DatePicker datePicker = (DatePicker) findViewById(R.id.Activity_AlertDialog_SetStartDate);
//  ... The rest of the AlertDialog, with buttons and all that stuff
alert.create().show()

The layout shows up in the AlertDialog, and that part works great. However, when I try to add this line, I get a null object reference error.

datePicker.setMinDate(System.currentTimeMillis() - 1000);

Here is the error message.

Attempt to invoke virtual method 'void android.widget.DatePicker.setMinDate(long)' on a null object reference

How can I fix this, or improve my code in another way? I really appreciate all the help I can get. Thanks!

Your problem is that your findViewById is looking in the wrong place for the DatePicker view. Calling findViewById in an activity will call it on the Activity's layout hierarchy, not the dialog's layout. You need to inflate the layout for the alert dialog first, and then get a reference to the view. This can be acheived in a couple ways.

Probably the easiest is to inflate the view and get the reference before showing the dialog:

View dialogView = LayoutInflater.from(this).inflate(R.layout.activity_alertdialog_date, false);
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.Activity_AlertDialog_SetStartDate);

AlertDialog.Builder alert  = new AlertDialog.Builder(this);
alert.setView(dialogView);
//  ... The rest of the AlertDialog, with buttons and all that stuff
alert.create().show();

You could also get the view from the alert dialog after it's been created:

AlertDialog.Builder alert  = new AlertDialog.Builder(this);
alert.setView(R.id.Activity_AlertDialog_SetStartDate);
//  ... The rest of the AlertDialog, with buttons and all that stuff
AlertDialog dialog = alert.create();

dialog.show();
DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.Activity_AlertDialog_SetStartDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM