0

It is okay to use Parcelable, Realm, and GSON in one project in Android development? I'm just wondering how to implement it simultaneously because each of these libraries/frameworks has different annotations when making a POJO. Another one is Realm and Parcelable both persist data, so do I need to implement both?

vidalbenjoe
  • 921
  • 13
  • 37

2 Answers2

3

GSON used to have quirkiness with Realm and required the following config

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();

GSON uses field reflection to read data from objects, which means that on managed RealmObjects, your fields will be null value.

This is because GSON also does not offer the option of using accessors to obtain the data, but Realm proxies do not copy the data to memory.

If you need an object that can be sent through Retrofit with @Body annotation and is a managed RealmObject, when you need to do apiService.sendObject(realm.copyFromRealm(myObject));.


Parcelable is not necessary for RealmObject in most cases, because any object that is managed by the Realm is already persisted, and readily available anywhere as long as you have its primary key.

But if you need to make detached modifiable copies of data and you're bent on using an unmanaged instance of the class directly to build the object you intend to save, then you can easily create Parcelable class using Parceler library.



In short:

  • RealmObjects are easily persistable to Parcelable using Parceler, but you typically don't need it, you just send the primary key between Activities and not the whole object
  • GSON doesn't work well with managed objects, because GSON is kinda dumb so you need to make an in-memory copy first


Personally, I prefer to keep my API response and my RealmModels separate, it's easier if you rely on mapping to a more optimal schema.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

This should be no problem cause you can use multiple annotations to one method or one class. If an annotation have the same name, you should give it the exactly package name like @java.lang.Override

phil
  • 1,289
  • 1
  • 15
  • 24