Search code examples
kotlinlocaldate

How to "put" LocalDate into SQLite DataBase


I need to insert a Date Field into an SQLite Database.

I am using Kotlin and I chose LocalDate class to handle Date.

I've created a class which has a field LocalDate:

data class Pillola(..., val startDay: LocalDate = LocalDate.now())

Then I've tried to put data into the db using ContentValues as below:

    val values = ContentValues().apply{
        put(COLUMN_START_DAY, pillola.startDay)
    }

But I get error:

enter image description here

How can I fix or what other way can I use?


Solution

  • Use LocalDate without Room

    You can use the LocalDate.toString() method.

    It will store the date in a ISO-8601 format as mentioned in the documentation

    In your exemple, it will be the following

    val values = ContentValues().apply{
            put(COLUMN_START_DAY, pillola.startDay.toString())
        }
    

    ContentValues cannot have other types as mentioned in your error (Boolean, Byte, ByteArray, Double, Float, Int, Long, Short, String)

    When retrieving the string from your database you can simply use LocalDate.parse(String) to instantiate the string back to the LocalDate.

    Use LocalDate with Room

    Assuming you are using the Android ORM Room

    If you have an entity having a LocalDate

    
    @Entity(tableName = "my_entity")
    data class MyEntity(
        val date: LocalDate
    )
    
    

    You can use a LocalDate only if you registered a Converter that will automatically store it as a string and retrieving it as a LocalDate

    
    class LocalDateConverter {
        @TypeConverter
        fun localDateToString(localDate: LocalDate): String = localDate.toString()
    
        @TypeConverter
        fun stringToDateTime(localDate: String): LocalDate = LocalDate.parse(localDate)
    }
    
    

    Don't forget to register the convert using the @TypeConvertersannotation

    @TypeConverters(LocalDateConverter::class)
    abstract class MyDatabase : RoomDatabase()