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

前端 未结 7 1275
野性不改
野性不改 2020-11-29 00:03

This is how I am inserting data into database using Room Persistence Library:

Entity:

@Entity
class User {
    @PrimaryKey(autoGenerate = true)
    p         


        
7条回答
  •  -上瘾入骨i
    2020-11-29 00:41

    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 insertCallable = () -> userDao.insert(user);
        long rowId = 0;
    
        Future 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.

提交回复
热议问题