首页 > 解决方案 > 应用关闭时如何删除房间数据库?

问题描述

我试图在活动销毁时调用 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)

请帮助我,祝大家有个愉快的一天!

标签: androidkotlinandroid-room

解决方案


deleteDatabase(AppDatabase.DATABASE_NAME);

或者

new Thread(() -> AppDatabase.getInstance(NavigationActivity.this).clearAllTables()).start();    //clear all rows from database

推荐阅读