Realm, searching in String list

Asked by At

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.

1 Answers

1
Pavel Poley On Best Solutions

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;
    }