Android Architecture Components: Room — Custom Types

Paulina Szklarska
AndroidPub
Published in
2 min readNov 6, 2017

--

Hi! This is a third story in the series of the Android Architecture Components articles. If you haven’t already, you can read about basics in the Room (entity, DAO) here:

Also, you can check my previous post about relationships in Room here:

Today we’ll look more closely into custom types in your entities.

Introduction

Usually, the data you put into a database is a primitive type — int, String, float, etc. But sometimes there’s a need to put custom type, e.g. Date, Location, or your own class. To implement such a value into the database properly, you need to tell Room how should it convert your custom type to the primitive type. This is what @TypeConverter is for.

Type Converter

Let’s look at the example of model class Repo that we’d like to put into the database:

@Entity
public class Repo {
@PrimaryKey
public int id;
public String name;
public Date createdAt;

public Repo(int id, String name, Date createdAt) {
this.id = id;
this.name = name;
this.createdAt = createdAt;
}
}

Besides primitive id and name fields we also have createdAt field, which is a Date type. If we want to have this date saved, we need to create proper type converter:

public class DateConverter {

@TypeConverter
public static Date toDate(long dateLong) {
return new Date(dateLong);
}

@TypeConverter
public static long fromDate(Date date) {
return date.getTime();
}
}

In this class we have two methods annotated with @TypeConverter:

  • toDate() having long as the parameter and returning Date type
  • fromDate() which is opposite

Each converter method should have one parameter and return non-void value.

To make this converter working, you need to declare this type converter in your database class:

@Database(entities = { Repo.class }, version = 1)
@TypeConverters(DateConverter.class)
public abstract class RepoDatabase extends RoomDatabase {
...
}

Pro Tip: You can also define type converter in other places, e.g. if you declare converter above your DAO class, then only methods from this DAO will be affected.

Conclusion

Thanks to type converters we’re able to save non-primitive values into the database. We can specifically define how the data should be converted, so it can be easily put into the database by Room.

--

--

Paulina Szklarska
AndroidPub

Flutter GDE / Flutter & Android Developer / blogger / speaker / cat owner / travel enthusiast