android – Datepicker: How to popup datepicker when click on button and store value in variable-ThrowExceptions

Exception or error:

I want to show datepicker popup window. I have found some examples but i am not getting it properly. I have one button and i want that when i click on button the datepicker dialog should popup and after setting the date, the date should be stored in a variable. PLease provide me sample code or good links.

How to solve:

Make this class as the inner class in your activity

if you wanna set the current date as the date you see when you open your datePicker. You can get it like this

Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);

class StartDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener{
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        // Use the current date as the default date in the picker
        DatePickerDialog dialog = new DatePickerDialog(BookingFormActivity.this, this, startYear, startMonth, startDay);
 return dialog;

    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        // TODO Auto-generated method stub
        // Do something with the date chosen by the user
        startYear = year;
        startMonth = monthOfYear;
        startDay = dayOfMonth;


you can call this dialog by setting this method to onClick

  public void showStartDateDialog(View v){
    DialogFragment dialogFragment = new StartDatePicker();, "start_date_picker");


Try this.

Use this code in your button click. The date picker dialog will be shown.

            Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);
    System.out.println("the selected " + mDay);
    DatePickerDialog dialog = new DatePickerDialog(Registration.this,
            new mDateSetListener(), mYear, mMonth, mDay);;

Then, mDateSetListener class needs to be written.

class mDateSetListener implements DatePickerDialog.OnDateSetListener {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            // getCalender();
            int mYear = year;
            int mMonth = monthOfYear;
            int mDay = dayOfMonth;
            v.setText(new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("/").append(mDay).append("/")
                    .append(mYear).append(" "));


Please check this answer and vote.

Leave a Reply

Your email address will not be published. Required fields are marked *