插入房间持久化库Android Studio后获取RowID
我一直在为我的房间数据库持久化使用codelabs。现在,在将数据插入我的房间数据库后,我正在尝试获取最新的rowID。但是,我在存储库中尝试从AsyncTask返回rowID。
LogEntity.java
@Entity
public class LogEntity {
@PrimaryKey(autoGenerate = true)
private int id;
LogDao.java
public interface LogDao {
@Insert
long insert(LogEntity logEntity);
LogDatabase.java
@Database(entities = LogEntity.class, version = 1)
public abstract class LogDatabase extends RoomDatabase {
private static LogDatabase instance;
public abstract LogDao logDao();
public static synchronized LogDatabase getInstance(Context context){
if (instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(),
LogDatabase.class, "log_database").
fallbackToDestructiveMigration().build();
}
return instance;
}
}
LogRepository.java
public long insertLogs(LogEntity logEntity) {
new InsertLogAsyncTask(logDao).execute(logEntity);
return **
}
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) {
logDao.insert(logEntities[0]);
return logDao.insert(logEntities[0]);
}
}
我放了两个星号,因为我不确定要在这里做什么才能获得插入行ID,也不确定我的AsyncTask是否完全正确。
LogViewModel.java
public long insertLog(LogEntity logEntity){
return repository.insertLogs(logEntity);
}
MainActivity.java
long id = logViewModel.insertLog(logEntity);
我希望能够使用此最终id变量以供将来使用。
解决方案
您走的是正确的道路,但还不完全正确。 您应该将AsyncTask类声明为ViewModel的内部类,而不是DB。
在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;
}
}
相关文章