在roomDatabase中插入时获取自动生成的ID

时间:2019-04-14 06:50:28

标签: android android-room

获取会议室数据库中新插入的行的ID的最佳方法是什么?

  

我已经知道@insert可以返回很长的时间。

甚至可以通过AsyncTask实现吗?

DatabaseInitializer.java

    public  class DatabaseInitializer {

    private static roomDatabase rDb;

            public  DatabaseInitializer(Context context) {
              rDb=  roomDatabase.createDatabase(context);

            }
            public  void insertPlayer(String pname,String ppic) {
                Players player = new Players();
                player.setPname(pname);
                player.setPpic(ppic);
                 insertPlayer(player);

            }
            private static void insertPlayer(final Players player) {
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... voids) {
                         rDb.playerDao().insert(player);
                         return null;
                    }

                }.execute() ;
            }
        }

1 个答案:

答案 0 :(得分:0)

最后,我是这样做的:

 public  Long insertPlayer(String pname,String ppic) {
    Players player = new Players();
    player.setPname(pname);
    player.setPpic(ppic);
     return insertPlayer(player);
}
static Long playerId;
private static Long insertPlayer(final Players player) {
    try {
        new AsyncTask<Void, Void, Long>() {
            @Override
            protected Long doInBackground(Void... voids) {
                playerId = rDb.playerDao().insert(player);
                return playerId;
            }

            @Override
            protected void onPostExecute(Long pID) {
                super.onPostExecute(playerId);
            }

        }.execute().get();
    }catch (Exception ex){ex.printStackTrace();}
        return playerId;
}