jason
jason

Reputation: 3962

insert or update values from retrofit to realm

I am getting arraylist from retrofit with my custom class. I converted the same class to realm by extending RealmObject. But I am unable to add data or create object . How can I write/update the same data to realm?

My retrofit callback:

Callback<ArrayList<CustomModel>> callback);

Retrofit code:

 @Override
            public void success(ArrayList<CustomModel> mycustomListModel, Response response) {

                        realm.beginTransaction();
                        realm.copyToRealmOrUpdate(mycustomListModel);
                        realm.commitTransaction();
}

Upvotes: 2

Views: 3236

Answers (2)

Ilya Tretyakov
Ilya Tretyakov

Reputation: 7010

You can extend your CustomModel from RealmObject.

Then setup gson for proper parsing.

Gson gson = new GsonBuilder()
    .setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    })
    .create();

Now you can use your object with Retrofit. No need to create seperate class.

https://realm.io/docs/java/latest/#gson

Upvotes: 2

Eenvincible
Eenvincible

Reputation: 5626

  1. First things first: create a Plain Old Java Object (POJO) using an online Generator that converts your json String into a Java Object. Here is a link to the tool : jsonschema2pojo
  2. Create your Realm object which you will use to store your data. Now, since you are returning a LIST of data, you have to loop through and you cannot just store them without validating!!

Notice that the TYPE returned by the Retrofit is your POJO class and not your Model class.

Since the POJO class has the corresponding fields as the Model, you have to create a new Model object each time you loop through then pull the fields from the pOJO class and set them on the Realm model; then finally copyToRealm and commit your transaction.

I hope this helps you have an idea on how this works!!

Upvotes: 2

Related Questions