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;
}
}
添加回答
舉報