问题
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