以增量

时间:2016-09-05 13:25:21

标签: android realm

我有一个包含ID

的项目列表的领域对象
@SerializedName("products")
RealmList<ProductDialItem> products;
@SerializedName("previous_suppliers")
RealmList<SuppliersDialItem> previousSuppliers;
@SerializedName("tariffs")
RealmList<TariffsDialItem> tariffs;
@SerializedName("deposit_frequencies")
RealmList<SimpleDialItem> depositFrequencies;
@SerializedName("bank_codes")
RealmList<SimpleDialItem> bankCodes;
@SerializedName("gas_usages")
RealmList<SimpleDialItem> gasUsages;

依此类推,列表中的每个项目都有ID。服务器发送一个json响应,其值包含在对象中。

但我们也使用Last-Modified标头,因此服务器只发送更改的项目。我只想更新项目,而不是删除任何项目。

Tl; dr我如何只更新/添加项目到领域,但不删除它们

2 个答案:

答案 0 :(得分:0)

让对象包含:

class MyClass{

int x = 0;

int y = 0;

int z = 0;

}

然后如果您需要从Web增加变量:

MyClass finalObject = new MyClass();

MyClass tempObject = new Gson().fromJson(response,MyClass.class);

incrementObjects(tempObject,finalObject);

现在创建方法incrementObjects():

private void incrementObjects(MyClass obj1, MyClass obj2){
obj2.x += obj1.x;
obj2.y += obj1.y;
obj2.z += obj1.z;
}

答案 1 :(得分:0)

当您获得更新的数据响应时,可以在Realm上查询,

//Create RealmList when you get updated Data in your api response.
RealmList<YourModel> updatedData = yourResponseData.getData();

//Get data from localDatabase and Query on
RealmQuery<YourModel> where = mRealm.where(YourModel.class);

     for (int i = 0; i < updatedData.size(); i++) {

          //put condition to match data based on your database.
          where = where.notEqualTo(YourModel.NAME,updatedData.get(i).getName());
     }


//Now this where.findAll(); , will return list of data which is notEqual To updatedData 
//perform update operation with this or deleteFrom local Data and insert new/updated Data.

where.findAll();