繁体   English   中英

日期选择器的Android IllegalArgumentException

[英]Android IllegalArgumentException for Date picker

我用于活动的日期选择器在KitKat上崩溃了,但在其他所有较新的操作系统上都可以使用。 这是我在旧设备上遇到的异常:

java.lang.IllegalArgumentException:fromDate:Mon Apr 10 07:59:25 EDT 2017不早于Date:Mon Apr 10 07:59:25 EDT 2017

代码块堆栈跟踪指向:

private void showDatePicker(){
   DatePickerDialog datePickerDialog = new DatePickerDialog(
   getActivity(), this, calendar.get(Calendar.YEAR),  calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
   //this is where the crash happens
   datePickerDialog.getDatePicker().setMinDate(new Date().getTime());
   datePickerDialog.show();
}

请让我知道有关该问题的信息是否足够。 有什么解决办法吗?

我会延迟解决此问题:

private void showDatePicker(){
   DatePickerDialog datePickerDialog = new DatePickerDialog(
   getActivity(), this, calendar.get(Calendar.YEAR),  calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
   //this is where the crash happens
   datePickerDialog.getDatePicker().setMinDate(new Date().getTime() - 10000);
   datePickerDialog.show();

}

要解决此问题,请在实例化DatePickerDialog之前为minDate创建一个时间戳:

private void showDatePicker(){
   long now = System.currentTimeMillis();
   DatePickerDialog datePickerDialog = new DatePickerDialog(
      getActivity(), this, calendar.get(Calendar.YEAR),  calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
   datePickerDialog.getDatePicker().setMinDate(now);
   datePickerDialog.show();
}

由于API21之前版本的CalendarView和API21的calendarViewMode == MODE_HOLO的错误,导致发生此崩溃。

尽管setMinDate包含以注释突出显示的更正:

public void setMinDate(long minDate) {
    ...
    mMinDate.setTimeInMillis(minDate);
    // make sure the current date is not earlier than
    // the new min date since the latter is used for
    // calculating the indices in the adapter thus
    // avoiding out of bounds error
    Calendar date = mAdapter.mSelectedDate;
    if (date.before(mMinDate)) {
        mAdapter.setSelectedDay(mMinDate);
    }
    // reinitialize the adapter since its range depends on min date
    mAdapter.init();

setSelectedDay的检查仅将mMinDatemSelectedDate进行日期精度比较:

public void setSelectedDay(Calendar selectedDay) {
    if (selectedDay.get(Calendar.DAY_OF_YEAR) == mSelectedDate.get(Calendar.DAY_OF_YEAR)
            && selectedDay.get(Calendar.YEAR) == mSelectedDate.get(Calendar.YEAR)) {
        return;
    }

mSelectedDatemMinDate是同一天的点,因此mSelectedDate将保持不变(即,处于错误的状态mSelectedDate < mMinDate )。

然后,控制流将运行到mAdapter.init ,然后运行到getWeeksSinceMinDate 在此函数中,将以毫秒精度对mMinDatemSelectedDate进行比较:

private int getWeeksSinceMinDate(Calendar date) {
    if (date.before(mMinDate)) {
        throw new IllegalArgumentException("fromDate: " + mMinDate.getTime()
                + " does not precede toDate: " + date.getTime());
    }

并且由于mSelectedDatemMinDate之前的几毫秒内初始化,因此崩溃将发生。

在较新的实现中,此代码被重写,因此API21 +缺少此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM