AndroidDev123
AndroidDev123

Reputation: 370

Room type converter: Converting a String date to Long

I am trying to convert my string dates to be stored as long values in the Room database.

I created this as my type converter.

object DateTypeConverter {
@TypeConverter
fun toString(sd: String): Long? {
    val sdf = SimpleDateFormat(Constants.YYYY_MM_DD_HH_MM_SS, Locale.ENGLISH)
    return sdf.parse(sd).time
}

@TypeConverter
fun toLong(longDate: Long): String? {
    val sdf = SimpleDateFormat(Constants.YYYY_MM_DD_HH_MM_SS, Locale.ENGLISH)
    return sdf.format(Date(longDate))
   }
}

However when I check the database the dates are still stored as strings in this format 2020/10/30 12:48:34

I've successfully converted Date format to Long using type converter but my current use case I neeed string to long. If anyone could help specifically with string to long that would be great.

Just to clarify I already have Date to long converter working its not the solution to my current use case.

Upvotes: 0

Views: 413

Answers (1)

sergiy tykhonov
sergiy tykhonov

Reputation: 5113

I haven't seen the source code of Room's annotation processor, but I guess it uses Type converters just for custom types (not for String, Int and so on).

I guess annotation processor works like this during build:

  • It looks for classes with @Entity, and checks fields' types. For types like Int, String, Double and so on it just matches them to SQLite types (INTEGER, TEXT) and generates boilerplate Java-code for that. So it seems for these types any Type converters are just ignored.
  • For another types (Date and another types) it checks for Type converter since it doesn't know how to convert them to SQLite types. If there is no such a converter declared - you get an error, if there is - annotation processor generates Java code with mapping methods from Type converter. The same principle it uses for Dao-methods (conversion from SQLite supported-types to Custom types).

As a workaround you technically could make string-wrapper class (with single String field), use this class as a type instead of current String-type and to implement Type converter for values of this class from and to Long.

Upvotes: 1

Related Questions