jwBurnside
jwBurnside

Reputation: 867

Android Realm: Retrieve collection ids from realm Object

I have saved my User to the realm. When I query the user I get this object:

User{id=0, hairColor=Red, favoriteSongs=FavoriteSong@[16,17]}

When I want the list of favorite songs, realm makes it easy to get a list back:

mUser.getFavoriteSongs();

But I'd like to get an array of the user's favoriteSong ids. This will make it easy to pass in a bundle as an int[].

Is this possible in Realm?

Upvotes: 0

Views: 334

Answers (1)

Rafa0809
Rafa0809

Reputation: 1752

I would propose you two options:

  1. Create a helper responsible of iterate the list of Songs and return a list of ids.

    class SongHelper {
    
        public static List<Integer> getSongIds(List<Song> songs) {
            List<Integer> songIds = new ArrayList<>();
            for( Song song : songs )
               songIds.add( song.getId() );
    
            return songIds;
        }
    
    }
    
  2. Override the getFavoriteSongs method and make it return List<Integer> instead of List<Song> or create an additional method for this in the User.

Option 1 is more elegant. You should always keep your model classes as clean as possible. In other words, just declare attributes, getter and setters without business logic.

Upvotes: 1

Related Questions