Search code examples
androidperformancerealmrealm-mobile-platformrealm-list

Realm, searching in String list


I have an items (RealmObject) and they have barcodes (RealmList). I have to query which item contains a searched barcode.

public class Item extends RealmObject {
    @PrimaryKey
    private long id;
    private RealmList<String> barcodes;

I have tried this but its too slow because I have a lot of item and the items have several barcode:

for (Item item : realm.where(Item.class).findAll()) {
                    if (item.getBarcodes().contains(barcode)) {
                        itemId = item.getId();
                        return;
                    }
                }

Thanks in advance.


Solution

  • Not sure that list of primitive support querying, but you can create new class Barcode that extends RealmObject with String field

    public class Barcode extends RealmObject{
       private String barcodeId;
    }
    

    then replace RealmList<String> barcodes to RealmList<Barcode> barcodes then query like this

    RealmResult<Item> realmResult = realm.where(Item.class).equalTo("barcodes.barcodeId",barcode).findAll();
    

    Also you can add @Index annotation that will improve querying speed(but writing may be a bit slower) docs

    public class Barcode extends RealmObject{
          @Index
           private String barcodeId;
        }