I have an android app that uses room database and dagger. I tried all the answers I found on the internet, and this is my last resort as I'm on the week 2 of solving this problem.
My Setup:
com.example.app
|-configurations
|-AppComponent.kt
|-AppDB.kt
|-AppModule.kt
|-MyApp.kt
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
fun inject(baseViewModel: BaseViewModel)
}
@Database(entities = [
User::class
], version = 1, exportSchema = true)
abstract class AppDB : RoomDatabase() {
abstract fun userRepository(): IUserRepository
companion object{
@Volatile
private var db_instance: AppDB? = null
@Synchronized
fun getAppDBInstance(context : Context): AppDB {
return db_instance ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDB::class.java,
"TransitPayDB.db3"
).allowMainThreadQueries()
.build()
db_instance = instance
instance
}
}
}
}
class MyApp: Application() {
private lateinit var appComponent: AppComponent
override fun onCreate() {
super.onCreate()
appComponent = DaggerAppComponent.builder().appModule(AppModule(this)).build()
}
fun getAppComponent(): AppComponent {
return appComponent
}
}
@Module
class AppModule(private val application: Application) {
@Singleton
@Provides
fun getUserRepo(appDB: AppDB): IUserRepository {
return appDB.userRepository()
}
@Singleton
@Provides
fun getRoomDBInstance(context: Context): AppDB {
return AppDB.getAppDBInstance(context)
}
@Singleton
@Provides
fun provideAppContext(): Context {
return application.applicationContext
}
}
And in my Manifest, I added this:
android:name=".configurations.MyApp"
I have normal transaction when the phone is disconnected from the debugger. and also I can see the databases and data when Im debugging. but my problem is when I hit debug again, all the data are gone and I have to repopulate all the test data again.
is there something wrong with my configurations?
by the way this is how I inject my repositories:
open class BaseViewModel(application: Application) : AndroidViewModel(application) {
@Inject lateinit var userRepository: IUserRepository
init {
(application as MyApp).getAppComponent().inject(this)
sharedUserId = sharedPrefs.getInt("userId",0)
sharedCompanyId = sharedPrefs.getInt("companyId",0)
sharedRoleId = sharedPrefs.getInt("roleId",0)
sharedFullName = sharedPrefs.getString("fullName","")
sharedApiToken = sharedPrefs.getString("apiToken","")
}
}
Thanks in advance.
Okay, so this is a rookie mistake.
I have 'Clear app storage before deployment' option ticked. It needs to be unticked to prevent android studio from clearing apps storage.