Android DatePicker

Recently I wrote a tutorial on android notifications and there we touched dialog notifications. Android’s date picker is a type of dialog. This tutorial is to explain how to create a date picker dialog in android. This dialog will disable the background activity until the user select the date and click ‘done’ tab of the dialog shown.

Following are the steps to create date picker:

  1. Creating new project.
  2. Designing the layout with datepicker icon.
  3. Generate code to display datepicker dialog.

1. Creating a new project.

We have already seen this step multiple times. Refer Get User Input in Android tutorial to recollect those steps.

2. Designing the layout with datepicker icon.

Open the xml file for layout design from the path workspace/GetUserInput/res/layout/activity_main.xml.
Select the Graphic layout tab.
Drag and drop the EditText from ‘form widgets’ and set properties of the right panel.
While selecting the EditText, choose the one appropriate for the date type. There are several types of EditText for various input that are supposed to be entered by the user. Code will be like this,

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="56dp"
android:ems="10"
android:inputType="date" >
<requestFocus />

Drag and drop the ImageButton field from the ‘images and media menu’.
When we try to place this imagebutton, the icon has to be selected to display for imagebutton. For that we should save a datepicker icon into res.drawable folder. And then, we need to set properties nedded like onClick, Padding and so on. After completeting this step, the code will look like as follows,

<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText1"
android:layout_toRightOf="@+id/editText1"
android:contentDescription="@string/selectdate"
android:cropToPadding="true"
android:onClick="selectDate"
android:src="@drawable/ic_datepicker" />

Finally layout code will be like,

actvity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="selectDate" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="56dp"
android:ems="10"
android:inputType="date" >
<requestFocus />
</EditText>
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText1"
android:layout_toRightOf="@+id/editText1"
android:contentDescription="@string/selectdate"
android:cropToPadding="true"
android:onClick="selectDate"
android:src="@drawable/ic_datepicker" />
</RelativeLayout>

3. Generate code to display datepicker dialog

Import the needed classes and then create the instance of FragmentActivity.
Usually instance will be created for Activity class. But in this this application it is created for FragmentActivity. This helps our activity to create a fragment as a popup on top of the layout.

Creating subclass which extends DialogFragment class and implements DatePickerDialog.OnDateSetListener method. This subclass includes method to display the datepicker fragment to the user. It also has the method to handle the event on setting the date.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}

public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}

The onCreateDialog() method creates a calendar object. Using this object the current day, month and year that will be retrieved. This current instance will return to the activity to display the date picker with the current date by default. onDateSet() method calls the populateSetDate() with the selected date parameters.

This method will update the EditText field with the following code.

public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.editText1);
mEdit.setText(month+"/"+day+"/"+year);
}

The entire code is as shown below.

MainActivity.java

package com.javapapers.andoiddatepicker;

import com.javapapers.andoiddatepicker.R;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.DatePicker;
import android.support.v4.app.FragmentActivity;
import android.app.Dialog;
import android.app.DatePickerDialog;
import android.support.v4.app.DialogFragment;

import java.util.Calendar;

public class MainActivity extends FragmentActivity {

EditText mEdit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getSupportFragmentManager(), "DatePicker");
}
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.editText1);
mEdit.setText(month+"/"+day+"/"+year);
}
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}

public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
}

}

Date Picker Output

Date Picker Android Source Code

Android Date Picker Source Code

This Android tutorial was added on 11/10/2012.

Comments on "Android DatePicker" Tutorial:

  1. Rashi.. Coorg.. says:

    Nice one.. Thank u so much!

  2. swapnil says:

    Joe you have talent with logic.. keep it up.. :)

  3. Darshan says:

    Good one:)
    I need date picker dialog to appear in the following format(dd/mm/yyyy).
    Help me.

  4. Anonymous says:

    Dear Joe,
    This is to do with Eclipse IDE, when I start following the steps given in any sample, the demo code was not working, but when I download from the source code, it works perfectly. I would like to the reason, if you have any.

    Pls

    Regards
    Bala S

    • Joe says:

      If you go by demo code, you need to add required libraries, compile it and run. This should also work, but not sure why you have issue. Can you share the exact error you get?

      • Liberty says:

        Hello Joe,
        Thanks for tutorial. Can you please guide on adding the library that references the below

        import com.javapapers.andoiddatepicker.R;

        Thanks in advance

  5. Michael says:

    Just Great !!!
    Joe you’re so logic to use a public class into the main, congrats for your work, it’s perfect for me :)

    For information, I’ve searched for a long time a good example with a DatePicker, and finally your job is the best ^^

    Thanks !

  6. antony says:

    excellent. it saves my time.
    thank you very much dear.

  7. Joe Vim says:

    Hello Joe,

    I am a B.tech guy and have knowledge with core java.
    I want to learn mobile application.

    What should i learn to be a mobile app developer.

    Have you an idea about Leonardo-hlc.

    Can this language help me to be an mobile app developer.

  8. Harold Kumar Oreocookie Gupta says:

    Hello Sir, how about creating an article that integrates a calendar view?

  9. shweta says:

    Hello sir,
    I am very badly in need of displaying events after selecting a date on date picker.its a part of my project..please help me out.
    I am able to display date picker..but how about adding and displaying events?!!

  10. lavanya says:

    Hello joe,
    Its really helpfull for my project. But i need two date picker in my project like one for date of dirth and one more for date of joining. I tried with many ways but didn’t get the answer. Can u please help me for it.

    Thank you.

  11. Dilip Kumar N says:

    Nice Work Joe.

    Have figured out the solution after searching for it a long time. Thanks

  12. sawan says:

    If you can post something related to social networking sharing that will so useful for everyone. Specially Twitter integration in android with latest twitter SDK.

    Looking forward for your response.

  13. Noman says:

    Nice help.. I like this

  14. Gunaseelan says:

    Hi Joe,

    I have tried your example. It is good. I need a small modification help.

    My Scenario is as follows. I have a registration page and and some other pages that need the date Picker.

    If I can manage to write a separate class for DatePickerDialog, I can able to call this class whenever I need a datepicker. (Code Reusablility).

    I can imagine the reusability. But when it comes create a separate class for date picker, I can’t able to do.

    Help me to overcome this.

    Give me an example with separate class for datepickerdialog.

  15. kevin says:

    Joe – Awesome tutorial and worked 100% perfect! I just spend a couple hours fiddling with the datepicker and could not for the life of me pass the date to an edit text. Thank you so much for posting this!

  16. shishram says:

    Hi, joe

    i want to create one edit text and that will contain vehicle registration no. .so this registration no format should be like this- xx-00-x/xx-0000 it means first two characters and than two digits and then one or two character after that four digits .is it possible to set this format likewise we setting up the date format please suggest

    thanks alot

  17. Engin says:

    Awesome! Thank you!

  18. Saravanan says:

    Thanks a lot Joe. Its really helpful and save my time.

  19. Archana says:

    Thanks a lot Joe but how to use it when we need to use more than one Date.

  20. Rikhil Jain says:

    Same as datepicker if we need to do for time picker then what to do can you please upload that code.. Please help me

  21. NIlkash says:

    Thank you for such a good work… But why there is +1 in month attribute ….

  22. Bharat says:

    Hi Joe,
    Is there a way to dismiss the datepicker without getting its value when the back button is pressed? I have a button on my view which invokes the date picker & gets the value & populates it in a EditText box. When i press back button also, it is getting the value & populating instead of just dismissing the box.

  23. Jaydeep says:

    thanks Joe for this easy and helpful tutorial.
    examples with images are so helpful to us(beginners).

  24. Pavan Kumar says:

    very nicely explained thank you

  25. Jordan says:

    great Joe! Thank you for the journey.

  26. Prathap says:

    I am new yo andoid ,

    Could you please tell me solution for my problem,

    i.e “getSupportFragmentManager()” i got errors on that meathod , whay that error, and what i have to do ?

    Thank you.

  27. SreePreeti says:

    Joe
    is there a way to show both DatePicker and TimePicker in same app? because i tried, but i got unwanted results.

  28. lynn says:

    Hi, is there anywhere to put multiple datepicker in the same activity??

  29. Abidhusain says:

    Nice One…. Thank You Very Much.

  30. Abidhusain says:

    Yes that is Possible by Placing the above code into the Every EditText Click event.

  31. Anurag says:

    The code stops unexpectedly at run time at the beginning. Please provide some help.

  32. Dinesh says:

    Unfortunately stopped working.

    09-10 13:16:31.146: E/AndroidRuntime(885): FATAL EXCEPTION: main
    09-10 13:16:31.146: E/AndroidRuntime(885): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.javapapers.andoiddatepicker/com.javapapers.andoiddatepicker.MainActivity}: java.lang.ClassNotFoundException: Didn’t find class “com.javapapers.andoiddatepicker.MainActivity” on path: /data/app/com.javapapers.andoiddatepicker-1.apk

    • Dinesh says:

      I solved this myself. But I got another problem. SelectDateFragment class should be static as per the official android pickers document. It throws error, how did u execute this Joe?

  33. Abednego says:

    hey i ve got an error , i think its because i dont have the library for it.

    “import com.javapapers.andoiddatepicker.R; ”

    How can i get the library above??

    please i need the solving problem for this,,

    BIG THX

  34. kaska says:

    how come 2 public classes inside 1 j file?

  35. George says:

    The tutorial is very educative ,but am stuck trying to implement the same code with two instances of the datepicker where you select the first date store it somewhere in a variable and select another date from the same datepicker and get the diffrence and output in in a textview or rather toast kindly assist,thank you.

  36. Anonymous says:

    Hi Joe, great work. However it does not seem like the code is work. When I try to implemwent this I get the following error:

    The method show(android.app.FragmentManager, java.lang.String) in the type DialogFragment is not applicable for the arguments (android.support.v4.app.FragmentManager, java.lang.String).

    This is found on the selectDate Method. Can you please tell what is wrong with this. Thanks for your help.

  37. dina says:

    plesae share how to set mindate and maxdate for the datepicker.

  38. dina says:

    there is conflict between api level below 11 and above 11

  39. dina says:

    Master joe kindly consider my question
    and give some sort of solutions for settting min and max dates

  40. megha says:

    Thank you so much sir…..it really worked v well… :)

  41. Pradyumna Swain says:

    Thankz Joe. Details about Pickers (TimePicker, DatePicker) can also be found here.http://developer.android.com/guide/topics/ui/controls/pickers.html

  42. teja says:

    thanks a lot it helped my assignment

  43. sateesh says:

    Hi Joe,

    I get this error. can you help me please.

    The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)

    NOTE: i copied everything as it is as; still i get this message.

    Thanks for help in Advance

  44. Vinoth says:

    Thanks for your code.

  45. Aleandro says:

    Thank you, it was really useful!!!!!!!!!!!

  46. Daniel Warui says:

    Thank you Sir.I am a passionate learner in android and your code has helped my problem.

Your Comment

↑ Go to top