Arindam
Arindam

Reputation: 33

RealmResults filter query with Exact String

I have a realm database where a field postCategories contains random string type data fetched from server through JSON. Those String values looks similar to the followings:

Semester - I, Marketing, English Version, Short Question
B.Com., Semester - II, E-Commerce, English Version, Broad Question
Semester - III, Marketing, English Version, Short Question
Semester - IV, Company Law, Bengali Version, Short Question
.......

Now, I want to filter RealmResults only where postCategories contains Semester - Ior Semester - II or Semester - III or Semester - IVany one, separately. what should I do?

I tried following codes to find all data where postCategories contains Semester - I :

RealmResults<RealmTitle> realmTitles;
realmTitles = realm.where(RealmTitle.class)
            .contains("postCategories", "Semester - I").findAll();

but this gives all data of Semester - I, Semester - II, Semester - III and Semester - IV.

I can find a temporary Solution as follows.

realmTitles = realm.where(RealmTitle.class)
                .contains("postCategories", "Semester - I")
                .and().not()
                .contains("postCategories", "Semester - II").findAll();

This is to prevent Semester - II to be added with the Result. But this doesn't seems like a good solution. Please help me to find more appropriate solution of this.

Thank you. Any help will be highly appreciated.

Upvotes: 0

Views: 557

Answers (1)

GiorgosDev
GiorgosDev

Reputation: 1767

To Select Semester I or II or III or IV try filtering by pattern i.e. not to have 2 "Semester - I" in one postCategories:

realmTitles = realm
   .where(RealmTitle.class)
   .contains("postCategories", "Semester - I")
   .and().not().like("postCategories", "*Semester - I*Semester - *")
   .findAll();

If it is important to exclude Semester IV

realmTitles = realm
   .where(RealmTitle.class)
   .contains("postCategories", "Semester - I")
   .and().not().like("postCategories", "*Semester - I*Semester - *")
   .and().not().contains("postCategories", "Semester - IV")
   .findAll();

If you want to have only those which have i.e. only Semester I:

realmTitles = realm
   .where(RealmTitle.class)
   .like("postCategories", "*Semester - I")
   .or().contains("postCategories", "Semester - I,")
   .and().not().like("postCategories", "*Semester - *Semester - *")
   .findAll();

Upvotes: 1

Related Questions