From 91ed9a32079c6d430cf6f890520f2461b71fd33c Mon Sep 17 00:00:00 2001 From: hmalik144 Date: Sat, 12 Sep 2020 22:43:35 +0100 Subject: [PATCH] Create roomdatabase Create room database and all its modules --- roomdatabase | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 roomdatabase diff --git a/roomdatabase b/roomdatabase new file mode 100644 index 0000000..7d72a74 --- /dev/null +++ b/roomdatabase @@ -0,0 +1,60 @@ +// TODO: add these dependencies +// def room_version = "2.2.5" +// implementation "androidx.room:room-runtime:$room_version" +// kapt "androidx.room:room-compiler:$room_version" +// implementation "androidx.room:room-ktx:$room_version" + +@androidx.room.Database( + entities = [EntityItem::class], + version = 1 +) +abstract class $DATABASENAME$Database : androidx.room.RoomDatabase() { + + abstract fun getSimpleDao(): SimpleDao + + companion object { + + @Volatile + private var instance: $DATABASENAME$Database? = null + private val LOCK = Any() + + // create an instance of room database or use previously created instance + operator fun invoke(context: android.content.Context) = instance ?: synchronized(LOCK) { + instance ?: buildDatabase(context).also { + instance = it + } + } + + private fun buildDatabase(context: android.content.Context) = + androidx.room.Room.databaseBuilder( + context.applicationContext, + $DATABASENAME$Database::class.java, + "MyDatabase.db" + ).build() + } +} + +@androidx.room.Entity +data class EntityItem( + @androidx.room.PrimaryKey(autoGenerate = false) + val id: Int? +) + +@androidx.room.Dao +interface SimpleDao { + + @androidx.room.Insert(onConflict = androidx.room.OnConflictStrategy.REPLACE) + fun saveAllItems(items : List) + + @androidx.room.Query("SELECT * FROM EntityItem") + fun getAllItems() : androidx.lifecycle.LiveData> + + @androidx.room.Query("SELECT * FROM EntityItem WHERE id = :id") + fun getItem(id: Int) : androidx.lifecycle.LiveData + + @androidx.room.Query("DELETE FROM EntityItem") + suspend fun deleteEntries() + + @androidx.room.Delete + fun deleteEntry(item: EntityItem) +}