Type converters
allow access to custom data types that are stored in a single database column. Room disallows object refrences because they take place on the UI thread and are expensive.
Create a TypeConverter:
You can annotate the methods of arbitrary class using the @TypeConverter
annotation. You can use type converters to define conversions between data types in your plain old Java object (POJO), and column types in a SQLite database. You can reference annotated classes from different scopes using the @TypeConverters
annotation, for example from a @Database
, @DAO
, or @Entity
public class Converters {
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
To use the converter annotate with Database
@Database(entities = {User.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
Use:
User.java
@Entity
public class User {
...
private Date birthday;
}
UserDao.java
@Dao
public interface UserDao {
...
@Query("SELECT * FROM user WHERE birthday BETWEEN :from AND :to")
List<User> findUsersBornBetweenDates(Date from, Date to);
}
Dao
@Entity
@TypeConverters(DateConverter.class)
class MyEntity {
Date birthday;
}