插入房间持久化库Android Studio后获取RowID [英] Getting RowID after inserting in Room Persistence Library Android Studio

查看:65
本文介绍了插入房间持久化库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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆