Gk Mohammad Emon
Gk Mohammad Emon

Reputation: 6938

How to check if a table/class exists in Realm database in android?

In a scenario, I need to check that if my expected table/class exists in the realm database or not. Because if I do some queries like this using DynamicRealm -

  DynamicRealm  dynamicRealm = DynamicRealm.getInstance(myRealmConfig);

  dynamicRealm.where("myExpectedClass").findAll();

Then I'm getting an exception like that -

Class does not exist in the Realm and cannot be queried: myExpectedClass

So to prevent this exception, I need to make it sure first that it is existing in database or not

Upvotes: 0

Views: 642

Answers (2)

Gk Mohammad Emon
Gk Mohammad Emon

Reputation: 6938

I have just debugged and found some methods to check this case and made an exception free reusable method -

         /**
         * @param dynamicRealm      The source dynamic realm created using the same realm configuration.
         * @param clazzNameExpected The CASE-SENSITIVE name of the expected class we want to check whatever it is existing in
         *                          realm database or not.
         * @return
         */

       public static boolean isClassExistInRealmDB(DynamicRealm dynamicRealm,String clazzNameExpected) {
            return (dynamicRealm != null && dynamicRealm.getSchema() != null) &&
                    dynamicRealm.getSchema().contains(clazzNameExpected);
        }

Upvotes: 0

sdex
sdex

Reputation: 3743

You can use:

dynamicRealm.getSchema().contains("myExpectedClass")

Upvotes: 1

Related Questions