Search code examples
androidjsonrealm

How can update the Realm DB when the JSON updates


Hi friends i am new to the realm when ever my json updates i need to update my realm database too but i cant see the updated JSON values in the realm i am cant able to understand why it is happening like that please help me out

 final JSONArray userarray = response.getJSONArray("user");
                    final Realm invoicerealm = Realm.getDefaultInstance();
                    invoicerealm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
//                            realm.delete(Upcoming_requests_adapter.class);
                            invoicerealm.createAllFromJson(Upcoming_requests_adapter.class,userarray);
                        }
                    });

Solution

  • First of all if, you need to update your database, perspective RealmObject should contain a primary key on which update operation will be performed. That means-

    Upcoming_requests_adapter.java should have a primary key.

    If it contains a primary key then the following transaction will create a new RealmObject or will update an existing RealmObject depends on primary key.

    final Realm invoicerealm = Realm.getDefaultInstance();
    invoicerealm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.createOrUpdateAllFromJson(Upcoming_requests_adapter.class, userarray);
        }
    });