Reputation: 214
I have two models who (with relevant properties) look like this:
@PrimaryKey
String id;
String name;
RealmList<Song> songs;
@PrimaryKey
String id;
String name;
As you can see, a playlist can contain many songs, and a song can belong to many playlists.
In one portion of my app I am displaying all the songs in a RecyclerView with a RealmBaseAdapter. I accomplish this no problem with:
RealmResults<Song> songResult = realm.where(Song.class).findAll();
RealmSongsAdapter realmAdapter = new RealmSongsAdapter(getActivity().getApplicationContext(), songResult , true);
songAdapter.setRealmAdapter(realmAdapter);
My question is: how would I go about showing songs for only a certain playlist? Since Song.java has no reference to it's own playlists, I don't have a way to get a RealmResult based off the Playlist object. Ideally I would like something like:
Playlist playlist = realm.where(Playlist.class).equalTo("id", playlistID).findFirst();
RealmResults<Song> playlistSongs = playlist.getSongs();
But playlist.getSongs()
returns a RealmList<Song>
rather than a RealmResult<Song>
.
One solution I found would be to create a RealmQuery
based on the Song ids in the playlist, but that seems counter intuitive:
RealmQuery<Song> query = mRealm.where(Song.class);
for (Song song : playlist.getSongs()) {
query = query.or().equalTo("id", song.getId());
}
RealmResults<Song> results = query.findAll();
The other problem with this is I would have to re-create this query every time the playlist song list changes.
Is there an easier way? Thanks in advance!
Upvotes: 4
Views: 983
Reputation: 20126
Christian from Realm here. Currently there is unfortunately no other way than the one you found yourself if you don't want to maintain a RealmList<Playlist>
field on the Song
. That said we have a concept called Backlinks on our TODO which are exactly for use cases like this: https://github.com/realm/realm-java/issues/607
Upvotes: 1