How to save List of Data in Table Column in Room Using Type Converter & Gson

Ngima Sherpa
2 min readSep 30, 2021

Let’s say you have an entity user with multiple Address Lines. Something like this

And you want to same it in room database. By default Room entity supports only primitive types. So how we do it?

Sometimes, you need your app to store a custom data type in a single database column. You support custom types by providing type converters, which are methods that tell Room how to convert custom types to and from known types that Room can persist. You identify type converters by using the @TypeConverter annotation.

So let’s dive into step by step example that how we add support for ArrayList<String> in entity parameters.

STEP 1: Adding Gson dependency in your project

dependencies {
implementation 'com.google.code.gson:gson:2.8.8'
}

Please find latest version from Gson Github Repo.

If you’ve not added room then you could add following dependencies as well.

dependencies {
//...
def room_version = "2.3.0"

implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
}

You could find a decent getting started guide from Android Developers Official Documentation.

STEP 2: Create Type Converter that converts string to ArrayList and ArrayList to String using Gson

Let’s first add a Generic Extension Function to avoid boilerplate to create the TypeToken.

Now let’s add ArrayListConverter class and define two functions for converting ArrayList<String> to String back and forth using Gson.

Now we can use ArrayList<String> as a type of Entity Parameter 😍.

--

--