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

android - room database not created architecture components


I'm using android architecture component and MVVM , i'm using room for offline mode , this is my code for making the connection:

    @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
    }
}

this is my DAO class:

    @Dao
interface CategoryDao{
    @Query("select * from $db_categoryTable")
    fun getCatOffline():Single<List<Cat>>

    @Insert(onConflict = REPLACE)
    fun insert(cat:Cat)
}

this is my Cat class :

        @Entity(tableName = Const.db_categoryTable)
    data class Cat(
        @PrimaryKey(autoGenerate = true)
        @SerializedName("id")
        @Expose
        val id: Int,
        val date_update: String,
        val name: String,
        val numCards: Int,
        val uid: String
    )

and this is my model class :

    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>> {
        dbConnection= DbConnection.getInstance(MyApp.INSTANCE)!!
        categoryDao=dbConnection.CategoryDao()

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

    private fun getCatsOffline(): MutableLiveData<MutableList<Cat>> {
        Log.v("this","offline ");

        var list = MutableLiveData<MutableList<Cat>>();

        categoryDao.getCatOffline()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {subccess->
                    list+=subccess
                },{
                    error->
                    Log.v("This",error.localizedMessage)
                }
            )
        return list
    }

    private fun getCatsOnline(): MutableLiveData<MutableList<Cat>> {
        Log.v("this","online ");
        var list: MutableLiveData<MutableList<Cat>> = MutableLiveData()
        val getCats = ApiConnection.client.create(Category::class.java)

        getCats.getCats(sharedPrefManager.getUid(), dateChanges)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                { success ->
                    list += success.cats
                }, { error ->
                    Log.v("this", "ErrorGetCats " + error.localizedMessage);
                }
            )

        return list;
    }

    operator fun <T> MutableLiveData<MutableList<T>>.plusAssign(values: List<T>) {
        val value = this.value ?: arrayListOf()
        value.addAll(values)
        this.value = value
    }

}

the model class as you can see has two parts when it has an internet connection, it goes online and otherwise, it goes to offline.

the problem is, it created the database but when I download and browse it, it doesn't have any table and content in it, it's just an empty database so it doesn't get any value when it goes in offline mode.

what is wrong with this code?


Solution

  • Looking at your code above, it seems you are not inserting any data in your Room. You should also insert data in Room in getCatsOnline() so when you access Room, you would be able to get data.