[英]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
的檢查僅將mMinDate
和mSelectedDate
進行日期精度比較:
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;
}
mSelectedDate
和mMinDate
是同一天的點,因此mSelectedDate
將保持不變(即,處於錯誤的狀態mSelectedDate < mMinDate
)。
然后,控制流將運行到mAdapter.init
,然后運行到getWeeksSinceMinDate
。 在此函數中,將以毫秒精度對mMinDate
和mSelectedDate
進行比較:
private int getWeeksSinceMinDate(Calendar date) {
if (date.before(mMinDate)) {
throw new IllegalArgumentException("fromDate: " + mMinDate.getTime()
+ " does not precede toDate: " + date.getTime());
}
並且由於mSelectedDate
在mMinDate
之前的幾毫秒內初始化,因此崩潰將發生。
在較新的實現中,此代碼被重寫,因此API21 +缺少此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.