Java – No public RealmResults constructor?

No public RealmResults constructor?… here is a solution to the problem.

No public RealmResults constructor?

I

have a table with Realm objects and I’m calling Foo.
One of Foo's columns points to another Realm Object, Bar.
I want to query the table Foo and pick out all the Bar objects I need and add them to the RealmBaseAdapter.

However, as far as I know, RealmBaseAdapter only uses a list of RealmResults in its constructor.
How do I form Bar’s RealmResults without querying the Bar table?
Or, how do I query the Foo table and return the RealmResults for Bar?

For example, suppose you have a table with products and product segments, such as rice flowers, Jade rice flakes, fruit rings are all part of the Cereal products section. I want to query the product table by some specification and list all the product segments included in the results.

Solution

Since I couldn’t do this directly, I ended up making my own adapter.

 public class BarAdapter extends ArrayAdapter<Bar>  {

code to instantiate the adapter, inflate views, etc

}

This part is trivial and the only hard work that needs to be done is curating a query from Foo->Bar that will get me the results I want. It ends up looking like this

    // where fooType was what I wanted to ween out the Foo results on before
     selecting Bar objects.
    RealmQuery<Foo> fooRealmQuery = realm
            .where(Foo.class)
            .equalTo("fooType", "desired type")
            .or()
            .equalTo("fooType", "other type");
    RealmResults<Foo> fooList = fooRealmQuery.findAll();

List<Bar> barList = new ArrayList<Bar>();
    for (Foo foo : fooList) {

Bar bar = foo.getBar();

if (!barList.contains(bar)) {
            barList.add(bar);
            Log.d(TAG, "added " + bar.getName());
        } else {
            Log.d(TAG, "I already had that bar");
        }
    }

adapter = new BarAdapter(this, barList);
    listView.setAdapter(adapter);

Now everything is normal. Also, Realm is fast enough that I can query as soon as the adapter is created, and I don’t see a performance lag 🙂

Related Problems and Solutions