BRDroid
BRDroid

Reputation: 4388

Room database setup in Android Library module

I have an existing Android project in which I have created a new Android Library (offlineservicelibrary)(File/new/New module/Android library). In this library I want to create a room database.

I followed https://developer.android.com/training/data-storage/room and created Entity (OfflineData) and DAO(OfflineDataDao) setup for my database, but I am a bit confused about where to setup AppDatabase and how Link it to the library.

@Database(entities = arrayOf(OfflineData::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun getOfflineDataDao(): OfflineDataDao
}

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

In my Library I do not have any class which extends Application class. Should I be creating a new class which extends Application class and do the above steps there.

Please suggest on what I should be doing to get the Library setup with Room database please

This is my Project structure with Library

enter image description here

Upvotes: 1

Views: 2369

Answers (1)

Công Hải
Công Hải

Reputation: 5241

  1. Make DatabaseManager Singleton class inside your module. Use @JvmStatic help you call from Java without Companion
class DatabaseManager private constructor(private val dp: AppDatabase) {
    fun loadData() : List<OfflineData> {
        return dp.getOfflineDataDao().loadAll() // I assume you already defined loadAll method in DAO
    }

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

        @JvmStatic
        fun getInstance(context: Context): DatabaseManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: run {
                    val db = Room.databaseBuilder(
                        context,
                        AppDatabase::class.java, "database-name"
                    ).build()
                    DatabaseManager(db).also { INSTANCE = it }
                }
            }
        }
    }
}
  1. In other modules you need to use your database, you have to implementation offlineservicelibrary in gradle and pass context to it when call
DatabaseManager.getInstance(context).loadData()

Upvotes: 2

Related Questions