Skip to content

Instantly share code, notes, and snippets.

@tinmegali
Last active January 12, 2023 13:44
Show Gist options
  • Save tinmegali/d4a477785f01e57066915a44543db6ed to your computer and use it in GitHub Desktop.
Save tinmegali/d4a477785f01e57066915a44543db6ed to your computer and use it in GitHub Desktop.
Android Room @TypeConverter using Kotlin
@Database(entities = arrayOf(Note::class, User::class), version = 1)
@TypeConverters(Converters::class)
abstract class AppDatabse : RoomDatabase() {
abstract fun userDAO(): UserDAO
abstract fun noteDAO(): NoteDAO
}
package com.tinmegali.daggerwithkotlin.room
import android.arch.persistence.room.TypeConverter
import java.util.Date
class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return if (value == null) null else Date(value)
}
@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return date?.time
}
}
@dniHze
Copy link

dniHze commented Nov 23, 2017

thank you a lot

@sattha
Copy link

sattha commented Mar 22, 2018

thank you

@NelzkieCoder
Copy link

Thank you!

@jamesnwarner
Copy link

Awesome example.
Thanks! 👍

@NikolayKul
Copy link

It's better to declare Converters as a singleton in order not to create any extra objects. You shoud also mark all inner converter functions with @JvmStatic so Room can use them as regular static functions

@louis993546
Copy link

@NikolayKul like this?

class RoomConverters {

    companion object {
        @TypeConverter @JvmStatic
        fun meToString(me: MyEnum): String = ds.name

        @TypeConverter @JvmStatic
        fun sToMyEnum(s: String): MyEnum = MyEnum.valueOf(s)

        //Add more converters here, or make another class altogether
    }

}

@aouerf
Copy link

aouerf commented May 14, 2018

@louistsaitszho it's more along the lines of this:

object RoomConverters {

    @TypeConverter
    @JvmStatic
    fun meToString(me: MyEnum?) = ds?.name

    @TypeConverter
    @JvmStatic
    fun sToMyEnum(s: String?) = s?.let(MyEnum::valueOf)

    // Add more converters here, or make another class altogether
}

@louis993546
Copy link

@aouerfelli oh yea I can just skip the class. But I got 1 more question: what if it is not nullable? And what if both nullable and non-nullable exists? How should I handle Entity like this:

@Entity
data class ToBePush(
    @PrimaryKey val id: Int,
    val value: Int.
    val createDate: Date,
    val syncDate: Date? = null
)

Should I create more @TypeConverter functions for both Date and Date?, or should I just have one set for Date??

@aouerf
Copy link

aouerf commented May 15, 2018

@louistsaitszho it's better to have them nullable to handle all use cases.

@louis993546
Copy link

Awesome! Thanks.

@marco-silva0000
Copy link

marco-silva0000 commented May 30, 2018

How should we use the RoomConverters object?
here it is:
https://developer.android.com/training/data-storage/room/referencing-data

@filipkowicz
Copy link

please note that @aouerfelli approach will not work if you need to use object members (for example instance of moshi)

@VeerHan
Copy link

VeerHan commented Jan 29, 2019

please note that @aouerfelli approach will not work if you need to use object members (for example instance of moshi)

Please go into detail.

@lmj0011
Copy link

lmj0011 commented Aug 21, 2019

How should we use the RoomConverters object?
here it is:
https://developer.android.com/training/data-storage/room/referencing-data

@marco-silva0000 really appricate that. All of the examples I see on the internet never reference the official docs.

@EvgenBES
Copy link

EvgenBES commented Aug 30, 2019

Converter ArrayList to String (gson) / String (gson) to ArrayList

class ListStringConverter {

@TypeConverter
fun fromString(value: String): List<String> {
    val listType = object : TypeToken<List<String>>() {}.type
    return Gson().fromJson(value, listType)  

}

@TypeConverter
fun fromListLisr(list: List<String>): String {
    val gson = Gson()
    return gson.toJson(list)
}

}

@4gus71n
Copy link

4gus71n commented Jan 2, 2020

Converter ArrayList to String (gson) / String (gson) to ArrayList

class ListStringConverter {

@TypeConverter
fun fromString(value: String): List<String> {
    val listType = object : TypeToken<List<String>>() {}.type
    return Gson().fromJson(value, listType)  

}

@TypeConverter
fun fromListLisr(list: List<String>): String {
    val gson = Gson()
    return gson.toJson(list)
}

}

Wouldn't be easier to do just:

class Converters {
    @TypeConverter
    fun toListOfStrings(flatStringList: String): List<String> {
        return flatStringList.split(",")
    }
    @TypeConverter
    fun fromListOfStrings(listOfString: List<String>): String {
        return listOfString.joinToString(",")
    }
}

@james04gr
Copy link

Is there any way to Convert a single column of a table but in the same Type? Like from String to String?

@GuzRoman
Copy link

How can i do it here if data is ProfileDataResponceModel

Main Profile class
@Entity(tableName = "profile_list")
data class ProfileResponseModel(
@Embedded(prefix = "profile_")
val data: ProfileDataResponseModel,
val status: Int,
val message: String
)
ProfileData

data class ProfileDataResponseModel(
val uid: Int?,
val name: String?,
val surname: String?,
val position: String?,
val department: String?,
val phone: String?,
val email: String?,
val contacts: String?,
val home: String?,
val password: String?
)

@noelvillaman
Copy link

How do I create a converter of my own Object. Let us say I have an User object and I want to add this entity to the database

@entity
data class Users(val orderId: UUID, val orderDate: Date, val manager: Manager, val office: Office) {}

I have the Manager class and the Office class that I want to us a converter, how do I go about that?

Thanks

@noelvillaman
Copy link

to use*

@Enough7
Copy link

Enough7 commented May 31, 2022

For some reason converting kotlin.time.Duration does not work but java.time.Duration

@kuza2010
Copy link

Are there a generic Converter for enum? Or do we need write specific converter for each enum that used?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment