Search code examples
androidkotlinandroid-roomkotlin-android-extensionstypeconverter

Use Room's TypeConverters on multiple fields


I am currently developing a small Android application and I am facing a problem about using a same TypeConverters on two fields. Here are the fields I have :

@TypeConverters(DateConverters::class)
@NonNull
@ColumnInfo(name = "create_date")
var createDate: Date

@TypeConverters(DateConverters::class)
@NonNull
@ColumnInfo(name = "update_date")
var updateDate: Date

create_date and update_date are both Date objects into my model class, but they are stored as String into the database. In order to do that, I have created a DateConverters class :

object DateConverters {
    @TypeConverter
    fun toDate(value: String): Date {
        val simpleDateFormat = SimpleDateFormat(PATTERN, Locale.getDefault())
        return simpleDateFormat.parse(value)
    }

    @TypeConverter
    fun toString(value: Date): String {
        val simpleDateFormat = SimpleDateFormat(PATTERN, Locale.getDefault())
        return simpleDateFormat.format(value)
    }
}

But when I try to run my application, I have to following error message :

error: DateConverters() has private access in DateConverters

I also add that before, I only had a create_date field and I had no problem on app run.

Can you tell me what am I doing wrong ?

Thank you in advance !


Solution

  • It seems like the problem can be in either using object instead of class or in methods names of converter. I recommend you to rewrite DateConverters in the following way:

    class DateConverters {
        @TypeConverter
        fun fromString(value: String): Date {
            val simpleDateFormat = SimpleDateFormat(PATTERN, Locale.getDefault())
            return simpleDateFormat.parse(value)
        }
    
        @TypeConverter
        fun dateToString(value: Date): String {
            val simpleDateFormat = SimpleDateFormat(PATTERN, Locale.getDefault())
            return simpleDateFormat.format(value)
        }
    }
    

    Moreover, I recommend you to store values as Long not as String as it is described in samples and then use SimpleDateFormat in non-data level.