Room how can I convert a custom made object

a 夏天 提交于 2021-02-18 22:55:12

问题


I'm new to Room, and I'm not understanding how I should go about this. I have an Entity Movie and another Entity called ÙpcomingMovies.

    @Entity
    public class Movie {

        @PrimaryKey
        @NonNull
        public String id;

        @ColumnInfo
        public String name;

        @ColumnInfo
        public String title;
    }

    @Entity
    public class UpcomingMovies {

        @PrimaryKey(autoGenerate = true)
        public int id;

        @ColumnInfo
        public Movie movie;
    }

So I already know Room has a problem with converting Objects, but I still havent seen how to convert a custom one with TypeConverter. Probably I'm complicating something, but can someone give me a hand tackling this issue ? I'm not even sure if my UpcomingMovies table is well made.

Appreciate it


回答1:


What you need to do is tell Room how to convert your class into a type that it knows how to store, in most cases this can be a String representation.

Firstly create a class for your TypeConverters and within it declare a function that can convert your type to and from the type you want Room to store it as. Don't forget to annotate these functions.

class MyTypeConverters {

@TypeConverter
fun appToString(app: App): String = Gson().toJson(app)

@TypeConverter
fun stringToApp(string: String): App = Gson().fromJson(string, App::class.java)

}

Then all you need to do is tell Room about your TypeConverters when you declare your database

@TypeConverters(MyTypeConverters::class)
abstract class AppDatabase : RoomDatabase() {
..DAO declarations
}

That's it.



来源:https://stackoverflow.com/questions/52008883/room-how-can-i-convert-a-custom-made-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!