Skip to content Skip to sidebar Skip to footer

Filtering Realm Object In Android

So i've started to use Realm and everything works fine, well almost everything. I'm using a MultiAutoCompleteTextView to select some user (RealmObject) so here goes: this is my Fil

Solution 1:

Christian from Realm here. Unfortunately Realm currently doesn't support the Filter class due to our Thread restrictions (and Filter does it's job on a background thread). We have it on our TODO however and you can follow progress here: https://github.com/realm/realm-android-adapters/issues/79

Until then you have two options:

1) Perform the filtering the the UI thread. If you don't have that many items in Realm or the query is relative simple, you will probably find that this is fast enough. We already have keyboard apps using Realm that does it this way.

2) Instead of returning proper Realm objects, read whatever data you need to display and return that from the performFiltering() method instead.

Solution 2:

I implemented a solution. The filter I did was responsible of help an AutocompleteTextView. The strategy consists of create a wrapper class that encapsulates the fields of the realm objects you want to show. Also, it should contains the primary key so then you can retrieve the full object.

This is an example of the "wrapper" class:

publicclassRealmWrapper{

  private long oid;
  privateString representation;

  publicRealmWrapper(long oid, String representation) {
    this.oid = oid;
    this.representation = representation;
  }

  public long getOid() {
    returnthis.oid;
  }

  publicvoidsetOid(long oid) {
    this.oid = oid;
  }

  publicStringgetRepresentation() {
    return representation;
  }

  publicvoidsetRepresentation(String representation) {
    this.representation = representation;
  }

  @OverridepublicStringtoString() {
    return representation;
  }
}

And when you extract the entities from Realm you copy the results to the wrapper:

 List<RealmWrapper> newObjects = new ArrayList<>();
 for( User entity : (RealmResults<User>) queryResults ){
     newObjects.add( new RealmWrapper(entity.getOid(), entity.getName()) );
 }

And finally, when you got the RealmViewAdapter from the view, you retrieve the original object:

Useruser= Realm.getInstance(context)
          .where(User.class)
          .contains("oid",adapter.getOid)
          .firstResult(); 

I hope this help you!

Post a Comment for "Filtering Realm Object In Android"