我已经使用领域大约一年多了,在许多情况下,领域是构建 Android 数据库而不是使用 SQLite 的不错选择。我一直在将领域用于一对一、一对多的关系,这对它有好处。不过,一会儿就好了。我发现领域不会以一对多的关系更新我现有的数据。这就是我所做的。
此代码用于填充骨架数据或单元测试
private void initData() {
List<PackModel> packs = new ArrayList<>();
for (int i = 0; i < 1; i++) {
PackModel packModel = new PackModel();
packModel.id = i;
packModel.name = "Pack " + new Random().nextInt(100);
List<FoodModel> foods = new ArrayList<>();
for (int j = 0; j < 3; j++) {
FoodModel foodModel = new FoodModel();
foodModel.id = 0; // i set primary key 0, so in list should be 3 but when insert should be JUST one
foodModel.packId = i;
foodModel.name = "Food " + new Random().nextInt(100);
foodModel.stock = new Random().nextInt(100);
foodModel.price = new Random().nextInt(100);
foodModel.image = "hrrp";
foodModel.calorie = new Random().nextInt(100);
foodModel.createTime = System.nanoTime();
foods.add(foodModel);
}
packModel.foods.addAll(foods);
packs.add(packModel);
}
insertdb(packs);
}
正如您看到的 PackModel 列表,每个 PackModel 都有自己的食物。所以,我在 Realm 中编写如下代码。
private void insertdb(final List<PackModel> items) {
new AsyncTask<Void, Void, List<PackObject>>() {
@Override
protected List<PackObject> doInBackground(Void... params) {
final List<PackObject> packsObject = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
PackObject packObject = new PackObject();
packObject.id = items.get(i).id;
packObject.name = items.get(i).name;
List<FoodObject> foodsObject = new ArrayList<>();
for (int j = 0; j < items.get(i).foods.size(); j++) {
FoodObject foodObject = new FoodObject();
foodObject.id = items.get(i).foods.get(j).id;
foodObject.name = items.get(i).foods.get(j).name;
foodObject.createdTime = items.get(i).foods.get(j).createTime;
foodsObject.add(foodObject);
}
packObject.foods.addAll(foodsObject);
packsObject.add(packObject);
}
Realm realm = Realm.getInstance(RealmApplication.getRealmConfiguration());
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(packsObject);
}
});
return realm.copyFromRealm(realm.where(PackObject.class).findAll());
}
@Override
protected void onPostExecute(List<PackObject> items) {
super.onPostExecute(items);
Log.d("Test", "");
}
}.execute();
}
我在每个 PackObject 中有多个 FoodObject,我在这里做错了什么?我也使用领域.beginTransaction。realm.beginTransaction 和execute* 一样,只是execute* 是线程安全的。
我也使用 realm.insertOrUpdate(obj),但结果相同。
注意:我已阅读有关它的领域文档。所以不要判断我没有阅读他们的文档。
这是我的代码报告https://github.com/radiityagumay/realm-bug
谢谢