Artem_Iens
Artem_Iens

Reputation: 312

android Realm Gson ClassNotFoundexception Class.forName io.realm.<Type>RealmProxy

Trying to make json string from realm object using Gson, according to this SerializeToJson.java . And it used to work fine with realm 4.0, but not with realm 5.8.0 Getting java.lang.ClassNotFoundException: io.realm.LevelRealmProxy Am I missing somthing? Anyway, here is my code:

 public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        setUpRealm();
        checkProxy();
    }

    private void setUpRealm() {
        Realm.init(this);
    }

    private void checkProxy() {

        Realm realm = null;
        try {
            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;
                        }
                    })
                    .registerTypeAdapter(Class.forName("io.realm.LevelRealmProxy"), new LevelSerializer())
                    .create();

            // Serialize a Realm object to a JSON string
            realm = Realm.getDefaultInstance();
            Log.d("MyLogs", gson.toJson(realm.where(Level.class).findFirst()));

        } catch (ClassNotFoundException e) {
            Log.e("MyLogs", e.toString());
            e.printStackTrace();
        } finally {
            if (realm != null) realm.close();
        }
    }

RealmObject

public class Level extends RealmObject {

    String id;
    int order;

}

TopLevel Gradle

dependencies {
    classpath 'com.android.tools.build:gradle:3.3.0'
    classpath "io.realm:realm-gradle-plugin:5.8.0"
}

App level gradle

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    compileSdkVersion 28

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

dependencies {
    implementation 'com.google.code.gson:gson:2.8.5'
}

I found workaround though , by using copyFromRealm() for RealmObject instead of using registerTypeAdapter for Gson

Upvotes: 0

Views: 124

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81588

Since Realm 5.0.0, the proxy classes contain the FQN as a prefix of RealmProxy, instead of just the class simple name. So io.realm.LevelRealmProxy is now io.realm.yourpackage_to_the_realmobject_LevelRealmProxy (in order to support multiple RealmObjects with the same name in different packages).

Upvotes: 1

Related Questions