NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Monday 10 May 2010

Date and Time Picker Views | Android Developer Tutorial (Part 20)

Continuing my tutorials on some UI related stuff… In Part 16 & 17, I spoke about Simple ListView and Custom ListView. In Part 18, though it seems like a tutorial on Threads and Handlers, I have touched upon ProgressDialog, another view.


Here I would like to talk on the DatePicker and TimePicker that are bundled with the SDK. Both are very similar. So, I will talk only about DatePicker, but the sample code will have both.

Typically, we would want an end user to be able to set a date though a DatePickerDialog that pops-up on some user action. So, I have a button “Set Date” on the click of which a DatePickerDialog pops-up. Once the user selects a date and “sets” it, it is displayed back in a TextView field.

So, the code associated with the button is:

pickDate.setOnClickListener( new OnClickListener() {
@Override
    public void onClick(View v) {
        showDialog(DATE_DIALOG_ID);
    }
});

showDialog(…) is a method available on an Activity Itself. It just takes an integer to help decide which dialog should actually be shown. This is decided in the onCreateDialog(…) method that gets automatically invoked when showDialog(…) is called.

Here is the code for the same:

protected Dialog onCreateDialog(int id){
    switch(id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, dateListener, year, month, day);
        case ….
    }
    return null;
}

In this method, when the int passed is DATE_DIALOG_ID, a new DatePickerDialog is passed along with the values for year, month and day. Where did I set values for these? In the onCreate(…) method itself, I have done this:

final Calendar cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);

Also note that a handle to a listener is expected to be given to the DatePickerDialog. I will come to this listener a little later.

I have also updated the Date - TextView with these values in the updateDate() method which is invoked in the onCreate(…) method itself.

private void updateTime() {
    timeDisplay.setText(new StringBuilder().append(hours).append(':')
    .append(min));
}

So far, what I have done is shown how to create a Dialog and set the date.

Once the dialog shows up, when a user sets the date and clicks ‘set’, the listener that is invoked in on the DatePickerDialog. The method is onDateSetListener whose handle is passed during the creation of the DatePickerDialog itself.

private DatePickerDialog.OnDateSetListener dateListener =
    new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int yr, int monthOfYear, int dayOfMonth) {
            year = yr;
            month = monthOfYear;
            day = dayOfMonth;
            updateDate();
     }
};

In this method, on the click on the dialog, we are setting the day, month, year values to the new values that the user selected and also calling the updateDate() method to refresh the TextView with what the user selected.

It is this simple.

Same thing can be done with the TimePicker as well. The only difference is that you can pass a Boolean variable to say whether you want the time in 24 hour or 12 hour pattern.

Here is the complete code for the same.



24 comments:

  1. Hi,
    I am trying to design a basic picker using html5 and javascript using SenchaTouchFramework for android web applications.I am trying to create a javascript for 3 slot picker but in vain.I am trying to do that based on hte examples given in senchaframework download DatePicker example.Can you provide a sample code for it.

    ReplyDelete
  2. Hi,

    Is it possible to disable the 'day' in the date picker? I wan't only the month and year, as in the expiry date of a credit card.

    Thanks,
    Prithvi

    ReplyDelete
  3. is it possible to display only month and year via datepicker

    ReplyDelete
  4. Hi Prithvi and Jatin,

    I do not see a default way of manipulating the date picker to not show the day. You may have to extend it and override to get a custom date picker with only year and month

    ReplyDelete
  5. Hello Sai Geetha, first of all I found your blog very interesting; I have a question about the DatePicker, what happens when I press the "Cancel" button? I mean, I'm developing an application which uses a DatePicker, but when I press the "Cancel" button the application doesn't work anymore... after debugging the code, I even saw that the application doesn't return to the onDestroy or onStop methods, so, how can I handle that event?
    Thanks in advance.

    ReplyDelete
  6. Maximiliano,

    The "cancel" button on the datepicker is just expected to close the datepicker dialog box. It is not expected to do anything else. Infact, it calls the cancel() method of the Dialog superclass which is same as dismiss(). Please see this link: http://developer.android.com/reference/android/app/Dialog.html#cancel()

    ReplyDelete
  7. Hello Sai Geetha, I really appreciate your reply, you are totally right I executed the DatePicker example from Android Developer's site and it's working fine, so obviously there is something wrong with my implementation; I use the DatePicker in several opportunities in my app, so I was trying to isolate the DatePicker in an activity so any time I need to use it I only start that activity (startActivityForResult). This works fine if I press the "Set" button, my problem is when I press the "Cancel" button, in that case the DatePicker dialog is closed but the app doesn't respond any more and if after that I press the "back" button then the debugger goes to the onActivityResult method of the calling activity. I tried to include the onStop and onDestroy methods in the activity which contains the DatePicker but they are both ignored. Do you have any suggestion for isolate the DatePicker in an activity which could be started for access it?
    Thanks in advance, and again, thanks for your reply. Cheers.

    ReplyDelete
  8. Hello Sai Geetha, I just want to tell you that I finally could solve my problem, I registered an OnDismissListener in the DatePickerDialog and in the method onDismiss I put the result and finish the activity. So, with that aggregate, any time that I need to present a DatePicker to the user I just start the activity DatePickerUtil and I wait for its result. Thanks a lot for your help. Cheers

    ReplyDelete
  9. I am getting a problem here. When setting both textviews the last one is always set (i.e. txt2 always gets a value instead on txt1)... Its doing it because initDateSetListener Method is set to final in its parameters... But it wont let me remove final keyword..

    public constructor() {
    initDateSetListener(txt1); //txt1 is a textview
    initDateSetListener(txt2); //txt2 is a textview
    }

    protected void initDateSetListener(final TextView displayView) {
    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    displayView.setText(String.valueOf(monthOfYear+1)+"/"+String.valueOf(dayOfMonth)+"/"+String.valueOf(year));
    }};
    }

    Please provide me a solution...

    ReplyDelete
  10. hai

    can u suggest me a way to create a custom date picker with only months and year.please it would be a great help for me

    ReplyDelete
  11. Hi
    Its really helpful.
    Thanks..

    ReplyDelete
  12. hiii... can u please tellmehow to schedule events by accepting time and date from the user...
    Thanks in advance...
    and this tutorial was very helful too!!!

    ReplyDelete
  13. hi Geetha,

    First thanks for the such a nice blog..

    I need to customize a time picker, I want time picker that increase the min with 15 min and not by 1 min as it does by default....

    Please suggest.....


    thanks in advance.

    ReplyDelete
  14. useful post , is there a way to see the combined date time view like iphone?

    ReplyDelete
  15. but in update display() i dont want append date that time hows its possible?
    in append old date also display but idont want old date..

    ReplyDelete
  16. Hello Sai Geetha,
    I have used the datepicker from android website and was able to select the date. My question here is how would you store the date selected in the SQLite database that i created.??

    I am having so much problems coding this and I have been googling from the past 1 week and I couldn't find the exact working code anywhere.

    Do you think you can help me with coding on
    "HOW TO STORE THE DATE PICKED FROM DATAPICKER INTO YOUR SQLITE DATABASE"

    ReplyDelete
  17. Can you post some samples on Timers...?

    ReplyDelete
  18. Hi,

    Is is possible to create the Date picker with Month and Year without customizing date picker(means by default Android Date picker)?

    ReplyDelete
  19. Hello Geeta, I have a question i want to set blank value to date,month and year in date picker. if you have any idea kindly reply me .thanks in advance

    Thanks
    Gaurav

    ReplyDelete
  20. hai madam

    i have a question

    how to chat app can create create ..if any example pls send to my mail id

    ReplyDelete
  21. Dear Geeta,
    It is really nice ,can you please help me to use date and time picker both together.

    Thanks,
    Tikam

    ReplyDelete
  22. hi,
    At the end of the process we have date,month,year.Can someone please tell me
    1.How to combine the 3
    2.store them in sqlite
    3.perforn operations like selecting dates from 5-10-2012 to 5-11-2012

    Thanks in advance

    ReplyDelete
  23. hi Sai Geetha,
    I need a date picker to select only year(last 90days, current year, previous year) and all months. I need to extend DatePickerDialog. Please lemme have the code snippet for it.


    Thanks and regards,
    Nagaraj

    ReplyDelete