作者:H801_597 | 来源:互联网 | 2023-01-28 14:35
我试图通过新的android房间库更新我的数据库,但它无法正常工作.这是我的方法
@IgnoreExtraProperties
@Entity(tableName = CarModel.TABLE_NAME,
indices = {@Index(value = "car_name", unique = true)})
public class CarModel {
public static final String TABLE_NAME = "cars";
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "car_name")
private String name;
@ColumnInfo(name = "car_price")
private String price;
private String type;
private String position;
}
MainActivity.java
viewModel.isCarsEmpty().observe(MainActivity.this, new Observer() {
@Override
public void onChanged(@Nullable Integer rowCount) {
if (rowCount == 0) {
viewModel.insertItems(list);
} else {
viewModel.updateItems(list);
}
}
});
CarViewModel.java
public LiveData isCarsEmpty() {
return appDatabase.carDao().isDbEmpty();
}
public void insertItems(List carModels) {
new insertCarsAsyncTask(appDatabase).execute(carModels);
}
private class insertCarsAsyncTask extends AsyncTask, Void, Void> {
private AppDatabase db;
public insertCarsAsyncTask(AppDatabase appDatabase) {
db = appDatabase;
}
@Override
protected Void doInBackground(List... params) {
db.carDao().insertCars(params[0]);
return null;
}
}
public void updateItems(List list) {
new updateCarsTask(appDatabase).execute(list);
}
private class updateCarsTask extends AsyncTask, Void, Void> {
private AppDatabase db;
public updateCarsTask(AppDatabase appDatabase) {
db = appDatabase;
}
@Override
protected Void doInBackground(List... params) {
db.carDao().updateCars(params[0]);
return null;
}
}
CarDao.java
@Insert(OnConflict= REPLACE)
void insertCars(List cars);
@Update
void updateCars(List param);
@Query("SELECT count(*) FROM " + CarModel.TABLE_NAME)
LiveData isDbEmpty();
我做了调试,新数据来了,并调用viewModel.updateItems(list)方法.提前谢谢!
1> Kimmi Dhingr..:
确保要更新的行和要发送到更新的模型应具有您已定义为主键的相同ID.
2> Maperz..:
我很抱歉发布这个作为答案,但我不允许添加一个简单的评论,所以这是我的想法:
您是否尝试过只使用insertCars()
而不是updateCars()
?无论如何,看起来你的isCarsEmpty()
LiveData回调一直被触发,因为当观察者被调用时,数据库再次被改变.我不太确定你想要实现什么.