gpt4 book ai didi

Android Room 持久性库@Update 不工作

转载 作者:IT王子 更新时间:2023-10-29 06:19:32 26 4
gpt4 key购买 nike

我正在尝试通过新的 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;
}

主 Activity .java

viewModel.isCarsEmpty().observe(MainActivity.this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer rowCount) {
if (rowCount == 0) {
viewModel.insertItems(list);
} else {
viewModel.updateItems(list);
}
}
});

汽车 View 模型.java

public LiveData<Integer> isCarsEmpty() {
return appDatabase.carDao().isDbEmpty();
}
public void insertItems(List<CarModel> carModels) {
new insertCarsAsyncTask(appDatabase).execute(carModels);
}

private class insertCarsAsyncTask extends AsyncTask<List<CarModel>, Void, Void> {
private AppDatabase db;

public insertCarsAsyncTask(AppDatabase appDatabase) {
db = appDatabase;
}

@Override
protected Void doInBackground(List<CarModel>... params) {
db.carDao().insertCars(params[0]);
return null;
}
}

public void updateItems(List<CarModel> list) {
new updateCarsTask(appDatabase).execute(list);
}

private class updateCarsTask extends AsyncTask<List<CarModel>, Void, Void> {
private AppDatabase db;

public updateCarsTask(AppDatabase appDatabase) {
db = appDatabase;
}

@Override
protected Void doInBackground(List<CarModel>... params) {
db.carDao().updateCars(params[0]);
return null;
}
}

CarDao.java

@Insert(onConflict = REPLACE)
void insertCars(List<CarModel> cars);

@Update
void updateCars(List<CarModel> param);

@Query("SELECT count(*) FROM " + CarModel.TABLE_NAME)
LiveData<Integer> isDbEmpty();

我进行了调试,新数据出现并调用了 viewModel.updateItems(list) 方法。提前致谢!

最佳答案

确保您要更新的行和您发送到更新的模型应该具有您定义为主键的相同 ID。

关于Android Room 持久性库@Update 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45299625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com