Skip to content
Advertisement

Kotlin (null cannot be cast to non-null type) Custom Calendar Implementation

I am trying to use the library https://github.com/kizitonwose/CalendarView (which was made in Kotlin) in Java. In this library there is an example to select a date. In the example, it had shown to do this:

    private fun selectDate(date: LocalDate) {
    if (selectedDate != date) {
        val oldDate = selectedDate
        selectedDate = date
        oldDate?.let { exThreeCalendar.notifyDateChanged(it) }
        exThreeCalendar.notifyDateChanged(date)
        updateAdapterForDate(date)
    }
}

After trying to replicate this in my own android project, I wrote this:

    private void selectDate(LocalDate date){
        if(selectedDate != date){
            // oldDate is null
            // date is not null
            LocalDate oldDate = selectedDate;
            selectedDate = date;
            if (oldDate != null){
                calendarView.notifyDateChanged(oldDate);
            }
            calendarView.notifyDateChanged(date);
            updateAdapterForDate(date);
            }
        }

When my fragment launches, it calls the selectDate() method with today’s date as the parameter (which is not null). It gives an error on

calendarView.notifyDateChanged(date);

saying

 null cannot be cast to non-null type com.kizitonwose.calendarview.ui.CalendarAdapter

I am wondering how to achieve the same outcome

oldDate?.let { exThreeCalendar.notifyDateChanged(it) }

in Java or if there is something else incorrect with my code. Thanks for any help.

Advertisement

Answer

Note the type in the error message. It isn’t date which is null, but something of type CalendarAdapter, I would suspect

private val calendarAdapter: CalendarAdapter
    get() = adapter as CalendarAdapter

It looks like adapter should be set in setup, maybe you aren’t calling it?

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement