-
-
Save zamahaka/584963739a010842dfee90a545e34d1d to your computer and use it in GitHub Desktop.
Problem with type converters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Database.kt | |
@Database(entities = [User::class], version = 1) | |
@TypeConverters(*[DatabaseTypeConverters::class]) | |
abstract class Database : RoomDatabase() { | |
abstract val userDao: UserDao | |
} | |
object DatabaseTypeConverters { | |
@TypeConverter | |
@JvmStatic | |
fun userTypeListToString(types: List<UserType?>?): String = | |
GsonBuilder().apply { registerAdapterFor<UserType>() }.create().toJson(types) | |
@TypeConverter | |
@JvmStatic | |
fun stringToUserTypeList(name: String?): List<UserType?>? = name?.let { | |
GsonBuilder().apply { registerAdapterFor<UserType>() }.create().fromJson(it) | |
} | |
} | |
//UserData.kt | |
@Entity(tableName = UserDao.TABLE_NAME) | |
data class User @JvmOverloads constructor( | |
@PrimaryKey @ColumnInfo(name = COLUMN_ID) var id: Long? = null, | |
@ColumnInfo(name = COLUMN_NAME) var name: String? = null, | |
@ColumnInfo(name = COLUMN_EMAIL) var email: String? = null, | |
@ColumnInfo(name = COLUMN_TYPES) var types: List<UserType?>? = null | |
) | |
enum class UserType { GROWER, LAB, DISPENSARY, PATIENT, DOCTOR, SUPPLIER, TRANSPORTATION, GOVERNMENT } | |
object UserColumns { | |
const val COLUMN_ID = "id" | |
const val COLUMN_NAME = "name" | |
const val COLUMN_EMAIL = "email" | |
const val COLUMN_TYPES = "types" | |
} | |
//GsonExt.kt | |
internal inline fun <reified T : Enum<T>> GsonBuilder.registerAdapterFor() { | |
registerTypeAdapter(T::class.java, JsonDeserializer { json, _, _ -> parseEnum<T>(json) }) | |
} | |
private inline fun <reified T : Enum<T>> parseEnum(json: JsonElement): Enum<T>? = try { | |
enumValueOf<T>(json.asString.toUpperCase()) | |
} catch (e: Exception) { | |
null | |
} | |
inline fun <reified T> Gson.fromJson(json: String): T = | |
this.fromJson<T>(json, object : TypeToken<T>() {}.type) | |
/* | |
* Getting this error: | |
* Cannot figure out how to save this field into database. You can consider adding a type converter for it. | |
* | |
* Error corresponds to 'types' property of User | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment