Search code examples
androidandroid-roomandroid-architecture-componentsandroid-viewmodelandroid-mvvm

android - room database connection in Model class android architecture


i'm new in MVVM , i'm using android architecture components too .

this is my code, I'e written the online part and now I'm working on offline part that needs to use the room database .

this is my model class code :

    class CategoryModel(
    private val netManager: NetManager,
    private val sharedPrefManager: SharedPrefManager
) {
    var dateChanges: String = "null";

private lateinit var categoryDao: CategoryDao
private lateinit var dbConnection: DbConnection

fun getCats(): MutableLiveData<MutableList<Cat>> {
    var list = MutableLiveData<MutableList<Cat>>();

    if (netManager.isConnected!!) {
        list = getCatsOnline();
    } else {
        list= getCatsOffline();
    }
    return list
}

this is DbConnection class:

@Database(entities = arrayOf(Cat::class), version = 1)
abstract class DbConnection : RoomDatabase() {
    abstract fun CategoryDao(): CategoryDao

companion object {
    private var INSTANCE: DbConnection? = null

    fun getInstance(context: Context): DbConnection? {
        if (INSTANCE == null) {
            synchronized(DbConnection::class) {
                INSTANCE = Room.databaseBuilder(
                    context.getApplicationContext(),
                    DbConnection::class.java, Const.db_Name
                ).build()
            }
        }
        return INSTANCE
    }

    fun destroyInstance() {
        INSTANCE = null
    }
}

the problem is this , I need to make a connection with room database and it needs the context .

How can I make this connection ? how to access database from Model class ?


Solution

  • Easy way to obtain the Application if you don't want model related to Application,

    First implement your own Application

    class BaseApp : Application() {
        companion object{
            lateinit var INSTANCE:Application
        }
        override fun onCreate() {
            super.onCreate()
            INSTANCE = this
        }
    }
    

    Second use it like:

    DbConnection.getInstance(BaseApp.INSTANCE)
    

    Don't forget define the BaseApp in AndroidManifest:

    <application
        android:name=".BaseApp"
        ...>
        ...
    </application>