如何在IntentService中查询房间数据库而不抛出异常

问题描述 投票:0回答:2

我正在查询POJO,它不是来自在PreferenceFragment中启动的IntentService的Observed / Non-Live数据。但是,我的应用程序第二次崩溃并显示日志:

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:204)
    at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:232)
    at vault.dao.xxxDao_Impl.getAllNonLivePojoItems(xxxDao_Impl.java:231)

我想知道为什么我的程序会抛出这个异常。按照https://stackoverflow.com/a/23935791/8623507

我的数据库查询[s]在一个运行在自己的线程中的IntentService内,所以我应该是绿色的。这是我的代码:

Inside IntentService
--------------------

// ERROR OCCURS HERE
List<POJO> pojoList = localRepo.getAllNonLivePojoItems(); // <= ERROR POINTS HERE
    if (pojoList != null && pojoList.size() > 0) {
        for (Pojo pojo : pojoList ){
           // Do Long Running Task Here ....
    }

我还实例化了正在使用的对象,并从OnHandleIntent中的IntentService中的那些对象调用上述方法,如下所示:

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        LocalRepo localRepo = new LocalRepo(this.getApplication());
        PojoHelper pojoHelper = new PojoHelper(this, localRepo);

        if (LOGOUT.equals(action) && type != null) {
            Log.d(TAG, "onHandleIntent: LOGOUT");
            pojoHelper.logoutPojo();
        } 
        else if(DELETE.equals(action) && type != null){
            Log.d(TAG, "onHandleIntent: DELETE_POJO");
            pojoHelper.deletePojo(true);
        }
    }
}
android android-room intentservice hang
2个回答
1
投票

我假设您从AsyncTask onPostExecute()方法获得回调,该方法在UI线程上运行。禁止在UI线程内使用数据库或网络调用,因为它可以阻止UI。

执行您在新线程中访问数据库的代码。

例:

        Executors.newSingleThreadExecutor().execute(()->{
             //TODO access Database
         });

0
投票

我没有提到的一件事是该方法是在异步的响应回调方法中执行的

PojoWarehouse.processPojoItems(new AsyncPojoCallback() {
    @Override
    public void done(Exception e) {
        if (e == null) {
            // ERROR OCCURS HERE
            List<POJO> pojoList = localRepo.getAllNonLivePojoItems(); // <= ERROR POINTS HERE
            if (pojoList != null && pojoList.size() > 0) {
                for (Pojo pojo : pojoList ){
                // Do Long Running Task Here ....
            }
        } else
                Log.d(TAG, "done: Error Logging Out: " + e.getLocalizedMessage());
        }
    });

我无法在技术层面上解释为什么这样可以解决问题,但欢迎提出建议。

© www.soinside.com 2019 - 2024. All rights reserved.