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:
We have already seen this step multiple times. Refer Get User Input in Android tutorial to recollect those steps.
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,
<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>
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.
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); } } }
Android Date Picker Source Code
Comments are closed for "Android DatePicker".
Nice one.. Thank u so much!
Joe you have talent with logic.. keep it up.. :)
Good one:)
I need date picker dialog to appear in the following format(dd/mm/yyyy).
Help me.
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
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 !
excellent. it saves my time.
thank you very much dear.
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.
First you should choose a mobile OS. Since you have java knowledge its better to start with Android.
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?
Hello Sir, how about creating an article that integrates a calendar view?
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?!!
Sure Harold, will write it soon.
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/
Great, thank you sir. I look forward to seeing your article.
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.
Nice Work Joe.
Have figured out the solution after searching for it a long time. Thanks
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.
Nice help.. I like this
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.
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!
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
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
Awesome! Thank you!
Thanks a lot Joe. Its really helpful and save my time.
Thanks a lot Joe but how to use it when we need to use more than one Date.
Same as datepicker if we need to do for time picker then what to do can you please upload that code.. Please help me
Thank you for such a good work… But why there is +1 in month attribute ….
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.
thanks Joe for this easy and helpful tutorial.
examples with images are so helpful to us(beginners).
very nicely explained thank you
great Joe! Thank you for the journey.
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.
this is very simple try this tutorial—>http://hukum-android-lab.blogspot.in/2013/06/custom-date-picker-in-android.html
Joe
is there a way to show both DatePicker and TimePicker in same app? because i tried, but i got unwanted results.
Hi, is there anywhere to put multiple datepicker in the same activity??
Nice One…. Thank You Very Much.
Yes that is Possible by Placing the above code into the Every EditText Click event.
The code stops unexpectedly at run time at the beginning. Please provide some help.
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
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
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?
extend FragmentActivity not just Activity
I solved this using my way of implementation to display selected date
how come 2 public classes inside 1 j file?
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.
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.
plesae share how to set mindate and maxdate for the datepicker.
there is conflict between api level below 11 and above 11
Master joe kindly consider my question
and give some sort of solutions for settting min and max dates
Thank you so much sir…..it really worked v well… :)
thanks a lot it helped my assignment
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
Thanks for your code.
Thank you, it was really useful!!!!!!!!!!!
Thank you Sir.I am a passionate learner in android and your code has helped my problem.
Welcome Daniel, happy to know.
very nice, i am impressed