'Added code for room database , but it is not working

Want to use Room database but getting the error.

Database code

package com.nandini.android.workoutapp

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [HistoryEntity::class], version = 1)
abstract class HistoryDatabase : RoomDatabase() {

    abstract fun historyDao():HistoryDao

    @Volatile
    private var INSTANCE :HistoryDatabase?=null

    fun getInstance(context: Context):HistoryDatabase{
        synchronized(this){
            var instance=INSTANCE

            if(instance==null){
                instance= Room.databaseBuilder(
                    context.applicationContext,
                    HistoryDatabase::class.java,
                    "history_database"
                ).fallbackToDestructiveMigration().build()
                INSTANCE = instance
            }
            return instance
        }

    }
}

Added the line in the manifest file

android:name=".WorkOutineApp"

Added another app class

package com.nandini.android.workoutapp

import android.app.Application

class WorkOutineApp : Application() {

    val db by lazy {
        HistoryDatabase.getInstance(this)
    }
}

but, this code is giving error for calling .getInstance(this) method .



Solution 1:[1]

try this

  @Database(entities = [User::class,DisplayItem::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also {INSTANCE = it}
            }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java, "user_database"
            ).allowMainThreadQueries().build()
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Niaj Mahmud