我正在使用room数据库和改装实现recyclerview,在这里,虽然最初我的数据是在本地加载并保存在联机中,但如果我关闭应用程序并再次打开意味着,以前存储的数据不会被删除,因此应用程序会出现以前加载和当前加载的数据,我实现了deleteall,但这不是发生在我的情况下,所以请提供解决方案。。
dao.java文件
public interface RepoDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(List<RepoModel> repoList);
@Query("SELECT * FROM repositories")
LiveData<List<RepoModel>> getAllRepos();
@Query("DELETE FROM repositories")
void deleteAll();
}
数据库.java
@Database(entities = {RepoModel.class}, version = 1, exportSchema = false)
public abstract class RepoDataBase extends RoomDatabase {
public static final String DATABASE_NAME = "RepoDataBase";
public abstract RepoDao repoDao();
private static final int NUMBER_OF_THREADS = 4;
public static final ExecutorService databaseWriteExecutor =
Executors.newFixedThreadPool(NUMBER_OF_THREADS);
private static volatile RepoDataBase INSTANCE;
public static RepoDataBase getInstance(Context context) {
if (INSTANCE == null) {
synchronized (RepoDataBase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context, RepoDataBase.class, DATABASE_NAME)
.addCallback(roomDataBaseCallBack)
.fallbackToDestructiveMigration().build();
}
}
}
return INSTANCE;
}
/**
* Override the onCreate method to populate the database.
* For this sample, we clear the database every time it is created.
*/
private static RoomDatabase.Callback roomDataBaseCallBack = new RoomDatabase.Callback(){
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
databaseWriteExecutor.execute(() -> {
RepoDao repoDao = INSTANCE.repoDao();
repoDao.deleteAll();
});
}
};
}
存储库.java
public class ReposRepository {
private RepoDao repoDao;
private LiveData<List<RepoModel>> getAllRepos;
public ReposRepository(Application application) {
RepoDataBase dataBase = RepoDataBase.getInstance(application);
repoDao = dataBase.repoDao();
getAllRepos = repoDao.getAllRepos();
}
public LiveData<List<RepoModel>> getAllRepos()
{
return getAllRepos;
}
public void insert(final List<RepoModel> repoModel){
RepoDataBase.databaseWriteExecutor
.execute(() -> repoDao.insert(repoModel));
}
}
repoviewmodel.java文件
public class RepoViewModel extends AndroidViewModel {
private ReposRepository reposRepository;
private final LiveData<List<RepoModel>> mRepoModel;
public RepoViewModel(@NonNull Application application) {
super(application);
reposRepository = new ReposRepository(application);
mRepoModel = reposRepository.getAllRepos();
}
public LiveData<List<RepoModel>> getAllRepos()
{
return mRepoModel;
}
}
1条答案
按热度按时间2q5ifsrm1#
oncreate方法在数据库的生存期内只自动运行一次。如果在数据库存在时停止应用程序并重新启动它,它将不会运行。