1

Below is the date picker dialog in one of the fragment and I am getting the error shown below

Type mismatch: inferred type is Int but LocalDate was expected
on line:
viewModel.onDateSelected(year, month, dayOfMonth)

 private val datePickerDialog by lazy {
        DatePickerDialog(requireActivity(), R.style.DatePicker).apply {
            setTitle(R.string.select_date)
            datePicker.maxDate = LocalDate.now().minusDays(0).toMillis()

            setOnDateSetListener { _, year, month, dayOfMonth ->
                viewModel.onDateSelected(year, month, dayOfMonth)
            }
        }
    }
1
  • this indicates that your issue is in onDateSelected function of your view model....you are expecting a LocalDate but passing a int like year or month or dayOfMonth Commented Jul 30, 2022 at 19:12

1 Answer 1

0

As unowsp pointed out, seems that you need a localDate. Try something like:

setOnDateSetListener { _, year, month, dayOfMonth ->
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.YEAR, year)
        calendar.set(Calendar.MONTH, month)
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
        val localDate = LocalDateTime.ofInstant(calendar.toInstant(), calendar.timeZone.toZoneId())
            .toLocalDate()
        viewModel.onDateSelected(localDate)
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Ahmed Ahmedov, This code works and doesn't show any error. But when I go click the date field again to change the date, it doesn't return the previous date, instead shows the current date. How Can I return to the previously selected date
Hi, @TopaZ. You have to set or update the datePicker date. Check this: stackoverflow.com/a/29073839/466577. I am not sure what exactly model.onDateSelected() is doing, but more likely you will get the date chosen by the view model. If its a local date, you might want to extract components from it like: localDate.year localDate.month, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.