美文网首页
使用Room Persistence遇到问题

使用Room Persistence遇到问题

作者: 咸鱼Jay | 来源:发表于2017-09-22 14:50 被阅读56次

    当你在进行数据库插入或查询时会报如下错误信息:

    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.arch.persistence.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:143)
        at android.arch.persistence.room.RoomDatabase.beginTransaction(RoomDatabase.java:190)
        at cn.labelnet.android.roomdb.base.data.dao.UserDao_Impl.insertUser(UserDao_Impl.java:63)
        at cn.labelnet.android.roomdb.main.MainActivity.onItemClick(MainActivity.kt:53)
        at cn.labelnet.android.roomdb.main.adapter.MainAdapter$onBindViewHolder$1.onClick(MainAdapter.kt:53)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
    

    这是因为你写的下面代码是默认操作必须放在io线程,不能放在ui线程中做

    AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build();
    

    解决方式:

    • 1、把操作放在io线程中(官方建议)
    • 2、如果真要把操作放在ui线程中,就必须加个allowMainThreadQueries()方法,这样数据库的操作就可以在ui线程中使用了!
    AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").allowMainThreadQueries().build();
    

    相关文章

      网友评论

          本文标题: 使用Room Persistence遇到问题

          本文链接:https://www.haomeiwen.com/subject/ajdfextx.html