0
val db = Room.databaseBuilder(
        applicationContext,
        AppDatabase::class.java, "database-name"
    ).build()

Is it compulsory to create instance of database class using the aboove code in mainactivity? in android ROOM?

Pawan Acharya
  • 89
  • 1
  • 14
  • You need that code somewhere. `MainActivity` would be an unusual choice. For a tiny single-screen app, you might have it in a `ViewModel` subclass. For a larger project, a typical approach is to have a repository class that hides the database I/O away from the UI layer. – CommonsWare Oct 11 '19 at 11:24
  • You have to initialise ROOM database in *Repository class* where all task perform like insertTask, updateTask, deleteTask etc,. – Shreeya Chhatrala Oct 11 '19 at 11:27
  • you can read this post https://stackoverflow.com/questions/45912619/using-room-as-singleton-in-kotlin – Andi Tenroaji Ahmad Oct 11 '19 at 13:46

1 Answers1

-1

You can have singleton database class and use it directly throughout application. No need to create its instance again and again .

Whenever you need DB Object just simply use it like below

  db = AppDatabase.getInstance(activity.applicationContext)

Singleton Class

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(
    entities = [Abc::class],
    version = 1,
    exportSchema = false
)

@TypeConverters(CustomTypeConvertes::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun abcDao(): AbcDao

    companion object {

        private var INSTANCE: AppDatabase? = null

        private val lock = Any()

        fun getInstance(context: Context): AppDatabase {
            synchronized(lock) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(
                        context.applicationContext,
                        AppDatabase::class.java, "database-name"
                    ).addCallback(object : RoomDatabase.Callback() {
                        override fun onCreate(db: SupportSQLiteDatabase) {
                            Console.debug("database-name", "Database created")
                            super.onCreate(db)
                        }

                        override fun onOpen(db: SupportSQLiteDatabase) {
                            Console.debug("database-name", "Database opened")
                            super.onOpen(db)
                        }
                    })
                        .fallbackToDestructiveMigration()
                        .build()
                }
                return INSTANCE!!
            }
        }
    }

}

Ravindra Shekhawat
  • 4,275
  • 1
  • 19
  • 26