Getting RowID after inserting in Room Persistence Library Android Studio(插入房间持久化库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;
}
}
这篇关于插入房间持久化库Android Studio后获取RowID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:插入房间持久化库Android Studio后获取RowID
基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
