Reputation: 4388
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
Upvotes: 1
Views: 2369
Reputation: 5241
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 }
}
}
}
}
}
offlineservicelibrary
in gradle
and pass context to it when callDatabaseManager.getInstance(context).loadData()
Upvotes: 2