房间如何转换自定义对象 [英] Room how can I convert a custom made object

查看:65
本文介绍了房间如何转换自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Room的新手,我不了解该怎么做.我有一个实体 Movie 和另一个称为ÙpcomingMovies的实体.

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;
    }

所以我已经知道Room转换对象存在问题,但我仍然没有看到如何使用 TypeConverter 转换自定义对象.可能我正在使事情复杂化,但是有人可以帮我解决这个问题吗?我什至不确定我的UpcomingMovies表是否做得好.

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.

欣赏

推荐答案

您需要做的就是告诉Room如何将您的类转换为知道如何存储的类型,在大多数情况下,这可以是String表示形式.

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.

首先为您的TypeConverters创建一个类,并在其中声明一个函数,该函数可以将您的类型与您要Room进行存储的类型之间进行转换.不要忘记注释这些功能.

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)

}

然后您要做的就是在声明数据库时告诉Room有关您的TypeConverters的信息

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
}

就是这样.

这篇关于房间如何转换自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆