I am trying to use Room for my new app. But whenever I restart my app, I am unable to retrieve the old data. It looks like my app is creating a new instance of the database every time, but I am not sure why. Here are my classes based on MVP pattern.
Edit: I just checked again and I can see that the auto-generated Id for the Entity (MyModel) doesn't get reset to 1 but when I retrieve data I only get collection inserted in that session.
Dao
@Dao
public interface MyDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
List<Long> insertModels(List<MyModel> models);
@Query("SELECT * FROM MyModel")
List<MyModel> getModels();
}
Database
@Database(entities = {MyModel.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
public abstract MyDao myDao();
}
DatabaseModule
@Module
public class DatabaseModule {
@Provides
@Singleton
MyDatabase provideMyDatabase(Application context) {
return Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, "MyDB").build();
}
@Provides
@Singleton
MyDao provideMyDao(MyDatabase myDatabase) {
return myDatabase.myDao();
}
}
Data Source
@Singleton
public class MyDataSource {
MyDao mMyDao;
@Inject
public MyDataSource(@NonNull MyDao myDao) {
mMyDao = myDao;
}
}
Repository
@Singleton
public class MyRepository {
private final MyDataSource mMyDataSource;
@Inject
MyRepository(@Local MyDataSource myDataSource) {
mMyDataSource = myDataSource;
}
}
ApplicationComponent
@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, ApplicationModule.class, DatabaseModule.class})
public interface ApplicationComponent extends AndroidInjector<MyApp> {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
ApplicationComponent build();
}
}
App
public class MyApp extends DaggerApplication {
private ApplicationComponent mApplicationComponent;
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
mApplicationComponent = DaggerApplicationComponent.builder().application(this).build();
return mApplicationComponent;
}
}