【问题标题】:Updating realm object by increments按增量更新领域对象
【发布时间】:2016-09-05 13:25:20
【问题描述】:

我有一个领域对象,其中包含带有 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 我如何只更新/添加项目到领域,而不是删除它们

【问题讨论】:

  • 尝试创建一个自定义的 JsonSerializer,就像示例中的那样:stackoverflow.com/questions/6856937/…
  • 对象包含大约 30 个字段,难道没有更自动化的方式吗?
  • 我会给出另一个答案
  • 你不必更新RealmList,只需更新ProductDialItem/SuppliersDialItem/SimpleDialItemRealmList中的对应项就会改变。这是你想问的吗?

标签: android realm


【解决方案1】:

让对象包含:

class MyClass{

int x = 0;

int y = 0;

int z = 0;

}

那么如果你需要从网络上增加变量:

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;
}

【讨论】:

    【解决方案2】:

    当您获得更新的数据响应时,您可以在 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();
    

    【讨论】:

    • 但是我必须为每个领域列表单独执行此操作吗?大约有 30 个
    • 那么如果不这样做,您将如何识别更新了哪些记录/数据?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多