Saturday, June 22, 2013

DatePicker and TimePicker Dialog in Android

We can use Time Picker  and Date Picker   widget to select a time and date , but TimePickerDialog and DatePickerDialog  is a better choice to do that.

In this post I will discuss how to use DatePickerDialog and TimePickerDialog to select Date and Time.



DatePickerDialog In Android
                      





Here I have described briefly, the Example with full source code is given below after this.
 
Declare following Variables in your Activity/Class

static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID=1;

// variables to save user selected date and time
public  int yearSelected,monthSelected,daySelected,hourSelected,minuteSelected;
  
// declare  the variables to show the date and time whenTime and Date Picker Dialog first appears
private int mYear, mMonth, mDay,mHour,mMinute; 

In the constructor you can initiallise the variable to current date and time.

                
                    final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    mHour = c.get(Calendar.HOUR_OF_DAY);
                    mMinute = c.get(Calendar.MINUTE);



//call the method when you need to show DatePickerDialog
 showDialog(DATE_DIALOG_ID);
//call the method when you need to show DatePickerDialog
  showDialog(TIME_DIALOG_ID);

// Register  DatePickerDialog listener
 private DatePickerDialog.OnDateSetListener mDateSetListener =
                        new DatePickerDialog.OnDateSetListener() {
                 // the callback received when the user "sets" the Date in the DatePickerDialog
                            public void onDateSet(DatePicker view, int yearSelected,
                                                  int monthOfYear, int dayOfMonth) {
                               year
Selected = yearSelected;
                               monthSelected = monthOfYear;
                               daySelected = dayOfMonth;
                              Toast.makeText(getApplicationContext(), "Date selected is:"+daySelected+"-"+monthSelected+"-"+yearSelected, Toast.LENGTH_LONG).show();
                                                         }
                        };


   // Register  TimePickerDialog listener                 
                        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                            new TimePickerDialog.OnTimeSetListener() {
             // the callback received when the user "sets" the TimePickerDialog in the dialog
                                public void onTimeSet(TimePicker view, int hourOfDay, int min) {

                                    hourSelected = hourOfDay;
                                    minuteSelected = min;
                                   Toast.makeText(getApplicationContext(), "Time selected is:"+hourSelected+"-"+minuteSelected, Toast.LENGTH_LONG).show();
                                                                  }
                            };


// Method automatically gets Called when you call showDialog()  method
                        @Override
                        protected Dialog onCreateDialog(int id) {
                            switch (id) {
                            case DATE_DIALOG_ID:
                                return new DatePickerDialog(this,
                                            mDateSetListener,
                                            mYear, mMonth, mDay);
                            case TIME_DIALOG_ID:
                                return new TimePickerDialog(this,
                                        mTimeSetListener, mHour, mMinute, false);
                           
                            }
                            return null;
                        }
                        

Date And Time Picker Dialog Example with Full Source Code

In the example   I have 2 buttons  
1: Select Date - to show DatePickerDialog 
2: Select Time - to show TimePickertDialog
When user selects a Date and Time in respective Dialogs we will set the selected date and time in Respective buttons. We will set selected date in Select Date Button and selected time in Select Time Button(See the last Snapshot)


main.xml



DatePickerDialog In Android



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:textSize="25dp"
        android:layout_gravity="center_horizontal"
        android:text="Date And Time Picker Example" />

    <Button
        android:id="@+id/buttonSelectDate"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Date" />

    <Button
        android:id="@+id/buttonSelectTime"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Time" />

</LinearLayout>




DateAndTimePickerActivity.java

public class DateAndTimePickerActivity extends Activity
{

            Button btnSelectDate,btnSelectTime;
           
            static final int DATE_DIALOG_ID = 0;
            static final int TIME_DIALOG_ID=1;
           
          
      // variables to save user selected date and time
            public  int year,month,day,hour,minute;  

 // declare  the variables to Show/Set the date and time when Time and  Date Picker Dialog first appears
            private int mYear, mMonth, mDay,mHour,mMinute;
           
            // constructor
           
            public DateAndTimePickerActivity()
            {
                        // Assign current Date and Time Values to Variables
                        final Calendar c = Calendar.getInstance();
                        mYear = c.get(Calendar.YEAR);
                        mMonth = c.get(Calendar.MONTH);
                        mDay = c.get(Calendar.DAY_OF_MONTH);
                        mHour = c.get(Calendar.HOUR_OF_DAY);
                        mMinute = c.get(Calendar.MINUTE);
            }
           
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.date_and_time_picker);
                       
                        // get the references of buttons
                        btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
                        btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
                       
                        // Set ClickListener on btnSelectDate
                        btnSelectDate.setOnClickListener(new View.OnClickListener() {
                           
                            public void onClick(View v) {
                                // Show the DatePickerDialog
                                 showDialog(DATE_DIALOG_ID);
                            }
                        });
                       
                        // Set ClickListener on btnSelectTime
                        btnSelectTime.setOnClickListener(new View.OnClickListener() {
                           
                            public void onClick(View v) {
                                // Show the TimePickerDialog
                                 showDialog(TIME_DIALOG_ID);
                            }
                        });
                       
            }
           
           
            // Register  DatePickerDialog listener

             private DatePickerDialog.OnDateSetListener mDateSetListener =
                                    new DatePickerDialog.OnDateSetListener() {
                                // the callback received when the user "sets" the Date in the DatePickerDialog
                                        public void onDateSet(DatePicker view, int yearSelected,
                                                              int monthOfYear, int dayOfMonth) {
                                           year = yearSelected;
                                           month = monthOfYear;
                                           day = dayOfMonth;
                                           // Set the Selected Date in Select date Button
                                           btnSelectDate.setText("Date selected : "+day+"-"+month+"-"+year);
                                        }
                                    };

               // Register  TimePickerDialog listener                
                                    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                                        new TimePickerDialog.OnTimeSetListener() {
                                 // the callback received when the user "sets" the TimePickerDialog in the dialog
                                            public void onTimeSet(TimePicker view, int hourOfDay, int min) {
                                                hour = hourOfDay;
                                                minute = min;
                                                // Set the Selected Date in Select date Button
                                                btnSelectTime.setText("Time selected :"+hour+"-"+minute);
                                              }
                                        };


            // Method automatically gets Called when you call showDialog()  method
                                    @Override
                                    protected Dialog onCreateDialog(int id) {
                                        switch (id) {
                                        case DATE_DIALOG_ID:
                                 // create a new DatePickerDialog with values you want to show
                                            return new DatePickerDialog(this,
                                                        mDateSetListener,
                                                        mYear, mMonth, mDay);
                                // create a new TimePickerDialog with values you want to show
                                        case TIME_DIALOG_ID:
                                            return new TimePickerDialog(this,
                                                    mTimeSetListener, mHour, mMinute, false);
                                      
                                        }
                                        return null;
                                    }
                                    
}


TimePickerDialog In Android







   


Advance Android Topics

                   Customizing Toast In Android 
                   Showing Toast for Longer Time
                   Customizing the Display Time of Toast
                   Using TimePickerDialog and DatePickerDialog In android
                   Animating A Button In Android
                    Populating ListView With DataBase

                    Customizing Checkboxes In Android 
                    Increasin Size of Checkboxes
                    Android ProgressBar
                    Designing For Different Screen Sizes
                    Handling Keyboard Events 



More Android Topics:



Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

       Toast

                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android
 

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                           

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android




5 comments:

  1. Very useful, but can you please tell me how can i customize it like calender.

    ReplyDelete
  2. always the dialog start in 1900 01 jan can you help me hoe fix it?

    ReplyDelete
    Replies
    1. You need to initialize with current date. Write the code for it in constructor.

      Delete
    2. can you send me the code for disable past date ?

      Delete