Android DatePicker

Last modified on August 1st, 2014 by Joe.

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

Comments on "Android DatePicker"

  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

  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. Joe says:

    First you should choose a mobile OS. Since you have java knowledge its better to start with Android.

  9. 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?

  10. Harold Kumar Oreocookie Gupta says:

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

  11. 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?!!

  12. Joe says:

    Sure Harold, will write it soon.

  13. Joe says:

    Shwetha,

    You need to have a database and store the events and retrieve it.
    Check this article to know how to use a database in android:
    https://javapapers.com/android/using-database-from-an-android-application/

  14. Harold Kumar Oreocookie Gupta says:

    Great, thank you sir. I look forward to seeing your article.

  15. 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.

  16. Dilip Kumar N says:

    Nice Work Joe.

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

  17. 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.

  18. Noman says:

    Nice help.. I like this

  19. 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.

  20. 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!

  21. 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

  22. 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

  23. Engin says:

    Awesome! Thank you!

  24. Saravanan says:

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

  25. Archana says:

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

  26. 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

  27. NIlkash says:

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

  28. 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.

  29. Jaydeep says:

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

  30. Pavan Kumar says:

    very nicely explained thank you

  31. Jordan says:

    great Joe! Thank you for the journey.

  32. 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.

  33. SreePreeti says:

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

  34. lynn says:

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

  35. Abidhusain says:

    Nice One…. Thank You Very Much.

  36. Abidhusain says:

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

  37. Anurag says:

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

  38. 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

  39. 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

  40. 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?

  41. Dinesh says:

    extend FragmentActivity not just Activity

  42. Dinesh says:

    I solved this using my way of implementation to display selected date

  43. kaska says:

    how come 2 public classes inside 1 j file?

  44. 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.

  45. 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.

  46. dina says:

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

  47. dina says:

    there is conflict between api level below 11 and above 11

  48. dina says:

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

  49. megha says:

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

  50. teja says:

    thanks a lot it helped my assignment

  51. 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

  52. Vinoth says:

    Thanks for your code.

  53. Aleandro says:

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

  54. Daniel Warui says:

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

  55. Joe says:

    Welcome Daniel, happy to know.

  56. sarthal says:

    very nice, i am impressed

Comments are closed for "Android DatePicker".