Android房间-插入行的id-来自ViewModel
我正在使用Android Room,我想获取新插入行的ID。我已在模型类中声明了列:Android房间-插入行的id-来自ViewModel,android,Android,我正在使用Android Room,我想获取新插入行的ID。我已在模型类中声明了列: @PrimaryKey (autoGenerate = true) @ColumnInfo (name = "productID") int id; public class ProductModelView extends AndroidViewModel { private ProductRepository mRepository; public ProductModelView(Applicati
@PrimaryKey (autoGenerate = true)
@ColumnInfo (name = "productID")
int id;
public class ProductModelView extends AndroidViewModel {
private ProductRepository mRepository;
public ProductModelView(Application application) {
super(application);
mRepository = new ProductRepository(application);
}
public void insert(Product p) {
mRepository.insertProduct(p);
}
}
然后我就知道我可以用刀来检索它:
@Insert
long insert(Product p);
起初,我直接在视图中使用“线程”调用。正如你们所知,这不是推荐的方法。因此,我尝试将其更改为ModelView和repository。但我不知道怎么才能拿到这个身份证
我的存储库类:
public class ProductRepository {
private ProductDao mProductDao;
ProductRepository(Application application) {
AppDatabase db = AppDatabase.getDatabase(application);
mProductDao = db.pDao();
}
public void insertProduct(Product p) {
new insertAsyncTask(mProductDao).execute(p);
}
private static class insertAsyncTask extends AsyncTask<Product, Void, Void> {
private ProductDao mAsyncTaskDao;
insertAsyncTask(ProductDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final Product... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}
在我的活动中,我插入了如下新对象:
mProductModelView.insert(pc);
@Query("SELECT * FROM Product ORDER BY id DESC LIMIT 1")
LiveData<Product> getLastProductLive();
那么,我如何从“插入”中检索这个长值,并在我的活动中获取它呢?我想LiveData可能是一个很好的方法,但老实说,我不知道如何实现它:(最好的方法是使用LiveData。如果你想使用MVVM,不妨学习如何使用LiveData。很简单 在DAO接口中,声明如下方法:
mProductModelView.insert(pc);
@Query("SELECT * FROM Product ORDER BY id DESC LIMIT 1")
LiveData<Product> getLastProductLive();
通过使用LiveData,每当产品添加到表中时,它都会触发此方法,您可以获得最后一个插入行的id。dao的插入方法本身返回一个长变量,其中包含插入行的id。为什么不能使用它?
mProductViewModel.getLastProductLive().observe(this, product -> {
long lastInsertedRowId = product.getId();
}