AndreiBogdan
AndreiBogdan

Reputation: 11164

Android. Date Picker (spinner) doesn't display properly

I initialize my date picker as follows:

    if (question.getAnswers().size() > 0) {
        EBotAnswer ans = question.getAnswers().get(0);

        try {
            if (ans.hasMinDate()) {
                picker.setMinDate(ans.getMinDateInLocalDate().getTimeInMillis());
            }
        } catch (IllegalArgumentException e) {
        }
        try {
            if (ans.hasMaxDate()) {
                picker.setMaxDate(ans.getMaxDateInLocalDate().getTimeInMillis());
            }
        } catch (IllegalArgumentException e) {
        }

        Calendar startWithDate = null;
        if (ans.hasStartWithDate()) {
            startWithDate = ans.getStartWithDateInLocalDate();
        } else if (ans.defaultCalendarDateMin()) {
            startWithDate = ans.getMinDateInLocalDate();
        } else if (ans.defaultCalendarDateMax()) {
            startWithDate = ans.getMaxDateInLocalDate();
        } else if (ans.defaultCalendarDateStartWith()) {//This is somewhat redundant
            startWithDate = ans.getStartWithDateInLocalDate();
        }
        if (startWithDate != null) {
            picker.updateDate(
                    startWithDate.get(Calendar.YEAR),
                    startWithDate.get(Calendar.MONTH),
                    startWithDate.get(Calendar.DAY_OF_MONTH));
        }
    }

But initially, the layout looks like so:

enter image description here

If I start turning the day spinner, the 8th of July shows up. enter image description here

Any ideas on why this is happening ?!

I tried calling picker.invalidate() or picker.requestLayout() or even picker.requestFocus() but nothing seems to be working.

Upvotes: 0

Views: 411

Answers (1)

Pankaj Kumar
Pankaj Kumar

Reputation: 82958

Check the value of startWithDate.get(Calendar.DAY_OF_MONTH). It may not valid for the cases which you applied to DatePicker, like max range.

To handle it properly, you can show minimum date or maximum date in case of input is out-of-range

if (startWithDate != null
        && (startWithDate.getTimeInMillis() < picker.getMaxDate())
        && (startWithDate.getTimeInMillis() > picker.getMinDate())) {
    picker.updateDate(
            startWithDate.get(Calendar.YEAR),
            startWithDate.get(Calendar.MONTH),
            startWithDate.get(Calendar.DAY_OF_MONTH));
} else {
    // In case of invalid date set it to minimum
    startWithDate.setTimeInMillis(picker.getMinDate());
    // Or if you want to set it to maximum
    // startWithDate.setTimeInMillis(picker.getMaxDate());
    picker.updateDate(
            startWithDate.get(Calendar.YEAR),
            startWithDate.get(Calendar.MONTH),
            startWithDate.get(Calendar.DAY_OF_MONTH));
}

Upvotes: 1

Related Questions