插入Room Persistence Library Android Studio后获取RowID

时间:2019-05-29 06:35:45

标签: java android database android-room

我一直在使用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]);
        }
    }

我放两个星号,因为我不确定在这里要做什么以获取插入的RowID以及我的AsyncTask是否完全正确。

LogViewModel.java

    public long insertLog(LogEntity logEntity){
        return repository.insertLogs(logEntity);
    }

MainActivity.java

        long id = logViewModel.insertLog(logEntity);

我希望能够使用此最终id变量以备将来使用。

1 个答案:

答案 0 :(得分:0)

您处在正确的轨道上,但并不完全正确。 您应该将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;
    }
}