首页 > 解决方案 > 如何以及在何处关闭()我的数据库停止获取 E/SQLiteLog:(283)

问题描述

当我在数据库浏览器中打开数据库文件时,它是空的。我得到了这个 E/SQLiteLog: (283) 从 WAL 文件中恢复了 16 帧。使用 Room 保存数据并在应用程序关闭时将其填充回来是否合适,反之亦然。如果有人能提供帮助,我会很高兴,谢谢。

/这是我在 db 类中的实例化 /

public static synchronized NoteDataBase getInstance(Context context){

    if (instance == null) {
        instance = Room.databaseBuilder(context.getApplicationContext(),
                NoteDataBase.class , "note_database")
                .fallbackToDestructiveMigration()
                .build();
    }
    return instance;
}
} 
@Override
public void close() {
    super.close();
    instance = null;
}

public void backup(Context context) {
    instance.close();
    //......... backup the file
    getInstance(context);
}

/和我的存储库/

 public NoteRepository(Application application) {
    dataBase = NoteDataBase.getInstance(application);
    noteDao = dataBase.noteDao();
    allNotes = noteDao.getAllNotes();

}

/我的一些视图模型/

public class NoteViewModel extends AndroidViewModel  {

public NoteViewModel(@NonNull Application application)  {
    super(application);
    repository = new NoteRepository(application);
    allNotes = repository.getAllNotes();
}

public void insert(Note note) {
    repository.insert(note);
}

}

/还有我保存一些结果的片段/

private void saveNote(){

    String savedscore = finalScore.getText().toString();
    ArrayList<String> daycheks =  new ArrayList<>();
    for (int i = 0; i < itemList.size(); i++) {
        daycheks.add(itemList.get(i).toString());
    }

    Note note = new Note(savedscore , daycheks);
    model.insert(note);

    Toast.makeText(getContext() , "Result saved" ,Toast.LENGTH_SHORT).show();

}

标签: androiddatabasesqliteandroid-sqliteandroid-room

解决方案


我的解决方案是在我的主 ViewModel 的 onCleared 方法中关闭数据库,然后错误日志消失了。

class MainActivityViewModel @Inject constructor(private val reviewRepository: ReviewRepository,
                                            private val favoriteRepository: FavoriteRepository,
                                            private val firebaseService: FirebaseService,
                                            private val sharedPreferences: SharedPreferences,
                                            private val toiletDb: ToiletDb)
: ViewModel() {

// Close database when the ViewModel is cleared
override fun onCleared() {
    super.onCleared()
    toiletDb.close()
}

推荐阅读