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)
            }
        }
    }
TopaZ
  • 35
  • 3
  • 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 – unownsp Jul 30 '22 at 19:12

1 Answers1

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)
    }
Ahmed Ahmedov
  • 592
  • 12
  • 29
  • 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 – TopaZ Jul 30 '22 at 20:23
  • Hi, @TopaZ. You have to set or update the datePicker date. Check this: https://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. – Ahmed Ahmedov Jul 30 '22 at 20:35