1 回答
TA贡献1773条经验 获得超3个赞
您走在正确的轨道上,但还不完全正确。您应该将 AsyncTask 类声明为 ViewModel 的内部类,而不是数据库。
在 ViewModel 中添加一个 ID 变量,在 AsyncTask 中添加onPostExecute覆盖以处理执行结果。
LogViewModel.java
long mLastInsertedID;
private static class InsertLogAsyncTask extends AsyncTask<LogEntity, Void, Long>{
private LogDao logDao;
private InsertLogAsyncTask(LogDao logDao){
this.logDao = logDao;
}
@Override
protected Long doInBackground(LogEntity... logEntities) {
//you are now off the UI thread
logDao.insert(logEntities[0]);
return logDao.insert(logEntities[0]);
}
@Override
protected void onPostExecute(Long result) {
//Do whatever you like with the result as you are back on the UI thread
mLastInsertedID = result;
}
}
添加回答
举报