Update statement in Realm android

前端 未结 3 1282
盖世英雄少女心
盖世英雄少女心 2021-02-07 02:36

How should i update a already existing value using realm DB in android?

I have been trying to update it but it is adding as a new value only not overwritting it

相关标签:
3条回答
  • 2021-02-07 03:03
    Realm realm = Realm.getDefaultInstance();
        OrderedRealmCollection<Practice> orderedRealmCollection = 
                 realm.where(Practice.class)
                .contains("key", "matchig value")
                .findAll();
    
        if(orderedRealmCollection.size()!=0){
            Practice practice = orderedRealmCollection.first();
            Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    practice.setUpdate_practice_steps(""+steps);
                    realm.insertOrUpdate(practice);
                }
            });
        }
    
    0 讨论(0)
  • 2021-02-07 03:09

    You can user insertOrUpdate method to do this.Hope this helps

      Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
    
                        objectToEdit.setNewValue("string");
                        realm.insertOrUpdate();
                    }
                });
    
    0 讨论(0)
  • 2021-02-07 03:11

    Another way to update an existing object with all its fields in your Realm DB is using the method realm.copyToRealmOrUpdate():

    Object obj = new Object();
    obj.setField1(field1);
    obj.setField2(field2);
    realm.beginTransaction();
    realm.copyToRealmOrUpdate(obj);
    realm.commitTransaction();
    

    If your object has a Primary Key, this method will update the object automatically without duplicate objects :)

    More info: copyToRealmOrUpdate()

    0 讨论(0)
提交回复
热议问题