Retrofit + RealmList + Gson stuck in a loop until out of memory

六眼飞鱼酱① 提交于 2019-11-29 04:45:47

You need to configure an ExclusionStrategy for GSON as described here: https://realm.io/docs/java/latest/#gson

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

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

Update: From Realm 0.89 it should no longer be necessary to define the exclusion strategy, the below should be enough:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

I was facing the same issue and the accepted answer didn't work for me despite of having realm version above 0.87. I am posting this in case anyone else faces this issue and accepted answer doesn't work.

I got it working by converting RealmList<MyModel> to List<MyModel> using ream.copyFromRealm function which creates in-memory copy of realm objects.

Something like this should work:

RealmList<MyModel> myModelRealmObjects = realmDBManager.getModelObjects();
List<MyModel> myModelObjects = realm.copyFromRealm(myModelRealmObjects);

And then pass myModelObjects to retrofit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!