Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query In Realm Database : Find All Objects Containing Query String

I've a set of different type of Objects persisted in Realm Database. Now I want to Query certain type of Objects including all of the fields of that Object. The method I wrote below, is getting all of the declared fields of the Object and iterates on the fields to check if the given query string is contained.

It works fine for the String fields types but throws java.lang.IllegalArgumentException: Field 'documentCompletionStatus': type mismatch. Was STRING, expected INTEGER. for integer values since my search query object is string. I skip the Non-String values for now as a workaround but I'm curious if it's possible to search it in all of the fields.

For example, if the user wants to search an integer value targeting the "Age" field of the Objects, I cannot make it work this way.

public <T extends RealmObject> List<T> searchDatabase(Class<T> clazz, String searchQuery) {

    /* Begin Query */
    RealmQuery<T> query = realmDatabase.where(clazz).beginGroup();

    Field[] fields = clazz.getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {

        /* Skip NON-String Values */
        if (!fields[i].getType().equals(String.class)) {
            continue;
        }

        if (i == 0) {
            query.contains(fields[i].getName(), searchQuery, false);
        } else {
            query.or().contains(fields[i].getName(), searchQuery, false);
        }
    }

    /* Return All Objects Found */
    return query.endGroup().findAll();
}
like image 744
osayilgan Avatar asked Apr 22 '15 04:04

osayilgan


1 Answers

Christian from Realm here. The reason your code doesn't work is because contains() only work for String fields (http://realm.io/docs/java/api/io/realm/RealmQuery.html#contains-java.lang.String-java.lang.String-), so when you try to use contains() it with a integer field it will fail.

If you want to search for different datatypes you will need to cast them to such, something like:

public <T extends RealmObject> List<T> searchDatabase(Class<T> clazz, String searchQuery) {

    RealmQuery<T> query = realmDatabase.where(clazz).beginGroup();

    Field[] fields = clazz.getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {
        Class<?> type = fields[i].getType();
        String fieldName = fields[i].getName();

        if (i > 0) {
            query.or()
        }   

        if (type.equals(String.class)) {
            query.contains(fieldName, searchQuery)
        } else if (type.equals(Integer.class)) {
            query.equalTo(fieldName, Integer.parseInt(searchQuery))
        } else {
            ...
        }
    }

    /* Return All Objects Found */
    return query.endGroup().findAll();
}
like image 98
Christian Melchior Avatar answered Oct 17 '22 08:10

Christian Melchior