Home > Blockchain >  Multiple Local Databases in Android Kotlin Using Room and ViewModel
Multiple Local Databases in Android Kotlin Using Room and ViewModel

Time:12-09

How is possible to add multiple databases in room using ViewModel class? Do I need a different ViewModel class and a different @Entity and a different @Dao for each database, or can I use the same @Entity and @Dao of another database, sorry if the question is pretty obvious, thanks a lot in advance

I tried different Databases with the same @Entity, @Dao and ViewModel, Didn't work

I also tried Different everything, the database appeared but i couldn't query it, please help :(

CodePudding user response:

Yes, you will need a separate Entity class, and Dao class for each database in Room. This is because each database will have its own set of data, and the Entity and Dao classes are used to define the schema and provide access to the data in the database.

    // Define the Entity class for each database
@Entity(tableName = "data1")
data class Data1(
    @PrimaryKey(autoGenerate = true) val id: Int,
    val data: String
)

@Entity(tableName = "data2")
data class Data2(
    @PrimaryKey(autoGenerate = true) val id: Int,
    val data: String
)

// Define the Dao class for each database
@Dao
interface Data1Dao {
    @Query("SELECT * FROM data1")
    fun getAll(): List<Data1>

    @Insert
    fun insert(data: Data1)

    // Other database operations...
}

@Dao
interface Data2Dao {
    @Query("SELECT * FROM data2")
    fun getAll(): List<Data2>

    @Insert
    fun insert(data: Data2)

    // Other database operations...
}

// Define the ViewModel class for each database
class MyViewModel1: ViewModel() {
    val db1: Database1
    val db2: Database2

    init {
        db1 = Room.databaseBuilder(context, Database1::class.java, 
   "db1").build()
        db2 = Room.databaseBuilder(context, Database2::class.java, 
   "db2").build()
    }

    fun getDataFromDb1(): List<Data1> {
        return db1.data1Dao().getAll()
    }

    fun getDataFromDb2(): List<Data2> {
        return db2.data2Dao().getAll()
    }

    // Other database operations...
}
  • Related