Skip to content

Instantly share code, notes, and snippets.

@emreeran
emreeran / EntitySample.kt
Created June 5, 2018 06:25
Basic Room entity class sample in Kotlin
@Entity(tableName = "entity_sample",
foreignKeys = [
(ForeignKey(entity = User::class, parentColumns = ["id"], childColumns = ["userId"], onDelete = CASCADE)),
(ForeignKey(entity = Post::class, parentColumns = ["id"], childColumns = ["postId"], onDelete = CASCADE))],
indices = [
(Index(value = ["postId"], name = "EntitySamplePostIndex")),
(Index(value = ["userId", "postId"], name = "EntitySampleUserPostIndex", unique = true))
]
)
data class EntitySample(
@emreeran
emreeran / DbModule.java
Created June 5, 2018 05:57
Android Room database class sample using Dagger
@Module
public class DbModule {
@Singleton
@Provides
public SampleDb provideDb(Application application) {
return Room.databaseBuilder(application, SampleDb.class, "sample.db").build();
}
@Singleton
@emreeran
emreeran / EntitySample.java
Last active June 5, 2018 07:37
Room database basic entity class sample
// Define table name foreign keys and indices. Second index defines a unique pair.
@Entity(
tableName = "entity_sample",
foreignKeys = {
@ForeignKey(entity = User.class, parentColumns = "id", childColumns = "user_id", onDelete = ForeignKey.CASCADE),
@ForeignKey(entity = Post.class, parentColumns = "id", childColumns = "post_id", onDelete = ForeignKey.CASCADE)
},
indices = {
@Index(value = "post_id", name = "PostIndex"),
@Index(value = {"user_id", "post_id"}, name = "UserPostIndex", unique = true)
@emreeran
emreeran / Converters.java
Created June 5, 2018 04:18
Room Database type converter class sample
public class Converters {
// Date type conversion methods
@TypeConverter
public Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public Long dateToTimestamp(Date date) {
if (date == null) {
@emreeran
emreeran / SampleDb.java
Created June 5, 2018 04:15
Basic Room database class implementation in Java
// Define tables via entity classes, set database version
@Database(version = 1, entities = {User.class, Post.class})
// Add type converters
@TypeConverters(Converters.class)
abstract public class SampleDb extends RoomDatabase {
private static volatile SampleDb INSTANCE;
public static SampleDb getInstance(Context context) {
if (INSTANCE == null) {
synchronized (SampleDb.class) {