Search This Blog

Support my cause by downloading

Wednesday, 1 August 2012

Date picker in android

In android application development, picker and dialog has an important place. Today i am going to discuss how to create a simple date picker dialog and time picker dialog. All though i know i am very late to write about this basic concept, but i realize that even-though a lots of matter and article available on this but they lack in term of explanation. So here i go with my attempt.

We need two things here

1) Dialog picker (either date or time) Object

2) And call back so that we can capture date or time when user set date


We will set current date or time when picker will open first time using calender object. Creating Datepickerdialog object inside overridden method of activity ,oncreatedialog() is best way. It will handle the orientation change effectively and you will avoid window leak exception quite easily



Making a call back listener for Datepickerdialog 


      OnDateSetListener ondate = new OnDateSetListener() {  
           @Override  
           public void onDateSet(DatePicker view, int year, int monthOfYear,  
                     int dayOfMonth) {  
                Builder builder = new AlertDialog.Builder(DateAndTimePicker.this);  
                builder.setMessage("Selected date : " + year + "/"  
                          + (++monthOfYear) + "/" + dayOfMonth);  
                builder.setPositiveButton("OK", null);  
                builder.show();  
           }  
      };  

It will return the date when you will click select button of  Datepickerdialog. Now override onCreateDialog(int d) and return Datepickerdialog object

      @Override  
      protected Dialog onCreateDialog(int id) {  
           Calendar calendar = Calendar.getInstance();  
           switch (id) {  
           case 1:  
                DatePickerDialog datePicker = new DatePickerDialog(this, ondate,  
                          calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),  
                          calendar.get(Calendar.DAY_OF_MONTH));  
                return datePicker;  
                     }  
           return super.onCreateDialog(id);  
      }  

DatePicker in android
Date Picker View

Date Picker selected value
Selected date

Follow this link to download source   Download Source Code



                                            
Android News and source code