【问题标题】:Android Room @Query Insert Into getting Cannot access database on the main thread since it may potentially lock the UI for a long period of timeAndroid Room @Query Insert Into getting 无法访问主线程上的数据库,因为它可能会长时间锁定 UI
【发布时间】:2020-02-10 03:47:24
【问题描述】:

我正在执行一个需要长参数的 INSERT INTO 查询,但我得到一个“无法访问主线程上的数据库,因为它可能会长时间锁定 UI。”错误并相信我需要将其作为异步任务运行,但无法找到要遵循的模式。我正在寻找插入查询,但需要推入两个长值以供查询使用,其中这个值传入一个注释数组或类似的东西:

private static class InsertNoteRunAsyncTask extends AsyncTask<Note, Void, Void> {
    private NoteDao noteDao;

    private InsertNoteRunAsyncTask (NoteDao noteDao) {
        this.noteDao = noteDao;
    }

    @Override
    protected Void doInBackground(Note... notes) {
        noteDao.insert(notes[0]);
        return null;
    }
}

如何异步触发带有两个参数的@Query?

更新 构建数据库时我没有 .allowMainThreadQueries():

public static synchronized AppDatabase getInstance(Context context) {

    if (instance == null)
    {
        instance = Room.databaseBuilder(context.getApplicationContext(),
                AppDatabase.class, "user-database")
                .fallbackToDestructiveMigration()
                .addCallback(roomCallback)
                .build();
    }

    return instance;
}

【问题讨论】:

    标签: android android-room


    【解决方案1】:

    删除allowMainThreadQueries()。它将在你的后台线程上运行,所以你不需要使用asynctask()。

    【讨论】:

    • 我更新了问题以显示当我收到错误时没有使用 .allowMainThreadQueries()。
    【解决方案2】:

    我最终创建了一个新的异步类并像这样调整它:

    private static class InsertIntoNoteRunAsyncTask extends AsyncTask<Note, Void, Void> {
        private NoteDao noteDao;
    
        private InsertIntoNoteRunAsyncTask (NoteDao noteDao) {
            this.noteDao = noteDao;
        }
    
        @Override
        protected Void doInBackground(Note... notes) {
            int id = notes[0].getId();
            noteDao.insertInto(id);
            return null;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多