0

我将 ExecutorService 与 Android Room 一起使用以避免 insetAsyncTasks 中的多个。我正在使用这篇文章中的 Debanjan 示例:链接,但我对其进行了一些修改。

问题是我没有得到任何异常,但没有插入任何内容。

DaoAsync 处理器:

public abstract class DaoAsyncProcessor<T> {

public interface DaoProcessCallback<T>{
    void  onResult(T result);
}

private DaoProcessCallback daoProcessCallback;

public DaoAsyncProcessor(DaoProcessCallback daoProcessCallback) {
    this.daoProcessCallback = daoProcessCallback;
}

protected abstract T doAsync();

public void start(){
    new DaoProcessAsyncTask().execute();
}

private class DaoProcessAsyncTask extends AsyncTask<Void, Void, T> {

    @Override
    protected T doInBackground(Void... params) {
        return doAsync();
    }

    @Override
    protected void onPostExecute(T t) {
        if(daoProcessCallback != null)
            daoProcessCallback.onResult(t);
    }
}
}

存储库:

public void createUpdate(final Projects item){
    EncertDatabase.databaseWriteExecutor.execute(() ->{
        if(item!=null){
            if(item.getId()==null){
                encertDAO.insert(item);
            }
            else {
                encertDAO.update(item);
            }
        }else {
            Log.e("Krkec", "Item was null");
        }

    });
}

数据库:

public abstract class EncertDatabase extends RoomDatabase {
private static  volatile EncertDatabase INSTANCE;
public  abstract EncertDAO encertDAO();

private static final int NUMBER_OF_THREADS = 4;
public static final ExecutorService databaseWriteExecutor =
        Executors.newFixedThreadPool(NUMBER_OF_THREADS);

public static  EncertDatabase getDatabase(final Context context){
    if(INSTANCE== null){
        synchronized (EncertDatabase.class){
            if (INSTANCE ==null){
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(), EncertDatabase.class,"encertDatabase").fallbackToDestructiveMigration().build();
            }
        }
    }
    return INSTANCE;
}
}

我究竟做错了什么?

4

1 回答 1

0

使用 setQueryExecutor 将 executor 服务实例分配给 db builder 实例

于 2021-07-02T06:45:01.823 回答