插入 Room Persistence Library Android Studio

我一直在使用代码实验室来实现我的房间数据库持久性。现在我试图在将数据插入我的房间数据库后获取最新的 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 变量以供将来使用。


繁花不似锦
浏览 79回答 1
1回答

慕容3067478

您走在正确的轨道上,但还不完全正确。您应该将 AsyncTask 类声明为 ViewModel 的内部类,而不是数据库。在 ViewModel 中添加一个 ID 变量,在 AsyncTask 中添加onPostExecute覆盖以处理执行结果。LogViewModel.javalong mLastInsertedID;private static class InsertLogAsyncTask extends AsyncTask<LogEntity, Void, Long>{&nbsp; &nbsp; private LogDao logDao;&nbsp; &nbsp; private InsertLogAsyncTask(LogDao logDao){&nbsp; &nbsp; &nbsp; &nbsp; this.logDao = logDao;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected Long doInBackground(LogEntity... logEntities) {&nbsp; &nbsp; &nbsp; &nbsp; //you are now off the UI thread&nbsp; &nbsp; &nbsp; &nbsp; logDao.insert(logEntities[0]);&nbsp; &nbsp; &nbsp; &nbsp; return logDao.insert(logEntities[0]);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void onPostExecute(Long result) {&nbsp; &nbsp; &nbsp; &nbsp; //Do whatever you like with the result as you are back on the UI thread&nbsp; &nbsp; &nbsp; &nbsp; mLastInsertedID = result;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java