我有一个包含一些片段的应用程序。在其中一个片段中,我经常调用db(大约4-5个)但是当用户与屏幕交互时,它们遍布片段中的所有位置。例如,当按下一个按钮时,获取b类型的所有记录...等我知道我们应该在一个单独的线程中做所有数据库操作,我知道AsyncTask以及如何使用它此
我的问题是,由于我在多个方法中调用了db,因此创建一个新的异步任务只是为了在片段中的不同位置每次需要它时进行db调用都没有意义。有没有办法在片段中的不同位置进行多个db调用,使用干净简单的单个异步任务实现处理所有这些?
答案 0 :(得分:2)
这样的事情怎么样:
public interface DBRunnable {
public void executeDBTask();
public void postExecuteDBTask();
}
private class DBTask extends AsyncTask<DBRunnable, Void, DBRunnable> {
@Override
protected DBRunnable doInBackground(DBRunnable...runnables) {
runnables[0].executeDBTask();
return runnables[0];
}
@Override
protected void onPostExecute(DBRunnable runnable) {
runnable.postExecuteDBTask();
}
}
这将被称为:
new DBTask().execute(new DBRunnable() {
@Override
public void executeDBTask() {
// execute your db code here
}
@Override
public void postExecuteDBTask() {
// run your post execute code here
}
});
可以将DBRunnable保存在一个位置,以使代码更易于阅读和维护。