Movsar Bekaev
Movsar Bekaev

Reputation: 908

Conditional WHERE in realm

I'm moving my app from sqlite3 to realm.

In my old code the queries were collective, i.e. code checks some settings and contemplating those builds a proper query:

Pseudocode - how it was before:

var str_where = "alala";
IF (SOMETHING) {
    str_where += "asdfasdfdasf";
}else{
    if (ANOTHERTHING)
        str_where += "trampampam";
    else
        str_where += "blablabla";
}

query+= "WHERE " + str_where

EXECUTE(query);

And now I don't have any query strings to pass and execute. With the Realm my query looks like:

Pseudocode - how it looks like now:

IF (SOMETHING) {
    dbPhrases = realm.where(xPhrase.class)
    .contains("alala")
    .contains("asdfasdfdasf")
    .findAll();
}else{
    if (ANOTHERTHING)
         dbPhrases = realm.where(xPhrase.class)
        .contains("alala")
        .contains("trampampam")
        .findAll();
    else
        dbPhrases = realm.where(xPhrase.class)
        .contains("alala")
        .contains("blablabla")
        .findAll();
}

And it looks very ugly and messy

So Is there any way to use some variable or maybe RealmQuery (which I wasn't able to implement) to construct the query along the way and then execute it in the end as I was doing it until now?

Upvotes: 0

Views: 1501

Answers (1)

beeender
beeender

Reputation: 3565

Try

RealmQuery<xPhrase> query = realm.where(xPhrase.class).contains("alala");
if (SOMETHING) {
    query.contains("asdfasdfdasf");
} else if (ANOTHERTHING) {
    query.contains("trampampam")
} else {
    query.contains("blablabla");
}
dpPhrases = query.findAll();

Upvotes: 1

Related Questions