Mikin Patel
Mikin Patel

Reputation: 441

DatePicker date set in android

I need a date-picker dialog in my application. First, I open the date picker dialog box and I select the date. The next time whenever open Date pickerDialog, the date of date picker should be current date of device. However, it shows last selected date in dialog. Please help me to set the code. Here is my code as I have it now:

@Override
protected Dialog onCreateDialog(int id)
{
    switch (id)
    {
        case DATE_DIALOG_ID:

        Date d=new Date();
        Calendar c=Calendar.getInstance();
        c.setTimeZone(tz);          
        c.setTime(d);
        d=c.getTime();

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);

        DatePickerDialog datePicker 
            = new DatePickerDialog(this, datePickerListener, year, month, date);      

        return datePicker;          
    }
    return super.onCreateDialog(id);
}

private DatePickerDialog.OnDateSetListener datePickerListener 
            = new DatePickerDialog.OnDateSetListener()
{
    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
    {
        cors_year = selectedYear;
        cors_month = selectedMonth;
        cors_date = selectedDay;

        getDate("calledfromDialog");
        displaySunTime();
        displayChoghadiya("Day");
        displayTime(3, 1);
        dayButtonClicked();
        selected_DAY_NIGHT="Day";
    }
};

Upvotes: 0

Views: 2008

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 200130

Note that onCreateDialog was deprecated in v13, per the documentation:

Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

Which you would use along with this tutorial

However, if you want to stay with the DatePickerDialog, you can use code such as:

protected void onPrepareDialog (int id, Dialog dialog)
{
    DatePickerDialog datePickerDialog = (DatePickerDialog) dialog;
    // Get the current date
    datePickerDialog.updateDate(year, month, day);
}

This is because Android only calls onCreateDialog once per dialog to re-use the dialog. onPrepareDialog is called in order for you to set the state of the Dialog appropriately before it is shown.

Upvotes: 2

Related Questions