android - 应用关闭时如何删除房间数据库?
问题描述
我试图在活动销毁时调用 ViewModel 来删除表,但它不起作用,当我在活动停止时调用 ViewModel 时出现错误。
DAO接口
@Dao
interface NoteDAO {
@Query("select * from note_table")
fun getAllNote() : LiveData<List<Note>>
@Query("DELETE FROM note_table")
fun deleteAllData()
}
存储库
class NoteRepository(app:Application) {
private val noteDAO : NoteDAO
init {
val noteDatabase: NoteDatabase = NoteDatabase.getInstance(app)
noteDAO = noteDatabase.getNoteDao()
}
fun getAllNote():LiveData<List<Note>> = noteDAO.getAllNote()
fun deleteAllData() = noteDAO.deleteAllData()
}
视图模型
class NoteViewModel(app: Application): ViewModel() {
private val noteRepository: NoteRepository = NoteRepository(app)
fun deleteAllData() = noteRepository.deleteAllData()
fun getAllNote() : LiveData<List<Note>> = noteRepository.getAllNote()
class NoteViewModelFactory(private val application: Application) : ViewModelProvider.Factory{
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if(modelClass.isAssignableFrom(NoteViewModel::class.java)){
return NoteViewModel(application) as T
}
throw IllegalArgumentException("Unable construct viewmodel")
}
}
}
当我调用 onStop 方法时
override fun onStop() {
super.onStop()
noteViewModel.deleteAllData()
}
我得到了错误
java.lang.RuntimeException: Unable to stop activity {com.example.database/com.example.database.MainActivity}: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4624)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4594)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4669)
at android.app.servertransaction.StopActivityItem.execute(StopActivityItem.java:41)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
请帮助我,祝大家有个愉快的一天!
解决方案
deleteDatabase(AppDatabase.DATABASE_NAME);
或者
new Thread(() -> AppDatabase.getInstance(NavigationActivity.this).clearAllTables()).start(); //clear all rows from database
推荐阅读
- dialogflow-es - 如何在不选择任何产品的情况下在谷歌助手中显示产品列表?
- html - IIS 上托管的视频无法在 Web 浏览器中播放
- mysql - 有数量范围的计数和总和
- django - 遵循Mozilla django教程时出现异常“unhashable type:'list'”
- r - 识别和总结 R 中的离散节点组
- python - RGB 到 HSI 转换 - 色调始终计算为 0
- xamarin - android.os.FileUriExposedException 错误 - XAMARIN
- c++ - OpenMP for循环并行问题
- python - wxPython:计算器不会在 Textctrlenter 中显示值
- java - Java 如果一个数字是 -0