Android Room - Get the id of new inserted row with auto-generate

情到浓时终转凉″ 提交于 2019-11-27 18:26:17

Based on the documentation here (below the code snippet)

A method annotated with the @Insert annotation can return:

  • long for single insert operation
  • long[] or Long[] or List<Long> for multiple insert operations
  • void if you don't care about the inserted id(s)

@Insert function can return void, long, long[] or List<Long>. Please try this.

 @Insert(onConflict = OnConflictStrategy.REPLACE)
  long insert(User user);

 // Insert multiple items
 @Insert(onConflict = OnConflictStrategy.REPLACE)
  long[] insert(User... user);

The return value of the insertion for one record will be 1 if your statement successfully.

In case you want to insert list of objects, you can go with:

@Insert(onConflict = OnConflictStrategy.REPLACE)
public long[] addAll(List<Object> list);

And execute it with Rx2:

Observable.fromCallable(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            return yourDao.addAll(list<Object>);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {
        @Override
        public void accept(@NonNull Object o) throws Exception {
           // the o will be Long[].size => numbers of inserted records.

        }
    });

Get the row ID by the following sniplet. It uses callable on an ExecutorService with Future.

 private UserDao userDao;
 private ExecutorService executorService;

 public long insertUploadStatus(User user) {
    Callable<Long> insertCallable = () -> userDao.insert(user);
    long rowId = 0;

    Future<Long> future = executorService.submit(insertCallable);
     try {
         rowId = future.get();
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return rowId;
 }

Ref: Java Executor Service Tutorial for more information on Callable.

In you Dao, the query insert return Long i.e. the rowId inserted.

 @Insert(onConflict = OnConflictStrategy.REPLACE)
 fun insert(recipes: CookingRecipes): Long

In your Model(Repository) class : (MVVM)

fun addRecipesData(cookingRecipes: CookingRecipes): Single<Long>? {
        return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
}

In your ModelView class: (MVVM) Handle LiveData with DisposableSingleObserver.
Working sourcer reference : https://github.com/SupriyaNaveen/CookingRecipes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!