Search code examples
javawrapperspotify

Is there a way to get track IDs of the tracks in a Spotify playlist using the Spotify JAVA API?


I've been using the Java wrapper for the Spotify API. I have been successful in retrieving the required playlist but I'm not able to get the track IDs of the tracks in the playlist.

Here is the code I'm using to get the playlist items.

playlistID = "37i9dQZF1DWXLeA8Omikj7";


        getPlaylistsItemsRequest = spotifyApi.getPlaylistsItems(playlistID).build();



        Paging<PlaylistTrack> playlistTrackPaging = getPlaylistsItems_Sync();
        PlaylistTrack[] items = playlistTrackPaging.getItems();

        System.out.println(items.length);
        for (int i = 0; i < items.length; i++) {
            System.out.println(items[i].getTrack().toString());
        }

The above code gives output in this format:

com.wrapper.spotify.model_objects.specification.Track@6c40365c

The alphanumeric in the end unfortunately isn't the track ID.

The PlaylistTrack object doesn't seem to have any way to get the track ID. Anyone know how I can get the track IDs? Been struggling with this for a while now. Thanks!


Solution

  • Yes

    Of course that's possible! :)

    Since v6.0.0-RC1 of spotify-web-api-java the PlaylistTracks, which are returned by your request, now contain an IPlaylistItem instead of a simple Track due to changes related to the new podcasts API, which made endpoint return types depend on the request's context.

    The current solution is to cast the items to their expected type. In your example, the println within the for-loop should look like this:

    System.out.println(((Track) items[i].getTrack()).getId());
    

    Depending on incoming pull requests, this could be improved in the future though: see the discussion in issue #201.