Vince VD
Vince VD

Reputation: 1581

How can i populate a RecyclerView with hashmap values?

Before i used an ArrayList for this, but because of duplicate Album issues (which i resolved before API29 by using DISTINCT and GROUP BY statements) which are not allowed anymore to use inside a query.

I got values like this in my RecyclerViews Adapter: myArrayList.get(position).getAlbum();

But now that i'm using a HashMap, how can i get a value by position which i get from the adapter?

Code for adding values in Hashmap

HashMap<Integer, Album> albums = new HashMap<>();

String[] projection2 = { MediaStore.Audio.Media.ALBUM_ID,
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media.IS_MUSIC};

String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";

String sort = MediaStore.Audio.Media.ALBUM + " COLLATE NOCASE ASC";

cursor = resolver.query(musicUri, projection2, selection, null, sort);

try {
      if (cursor != null) {
          cursor.moveToFirst();
          while (!cursor.isAfterLast()) {

                 int columnAlbumId = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
                 int columnAlbumName = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);

                 String albumId = cursor.getString(columnAlbumId);
                 String albumName = cursor.getString(columnAlbumName);

                 if(albums.containsKey(albumId) == false){
                   Album album = new Album(albumId, albumName);
                   albums.put(albumId, album);
                 }
                cursor.moveToNext();
          }
       }
    }catch (Exception e){
     Log.e(TAG, "Exception caught when creating ALBUM!", e);
     throw new Exception();
}

Upvotes: 1

Views: 351

Answers (1)

Themelis
Themelis

Reputation: 4245

By definition the HashMap is not sorted so how about a SortedMap? An implementation of a SortedMap is a TreeMap which sorts the entries according to keys (or a Comparator).

I believe that suits you since your map has integers as keys.

Edit: You can use a List or whatever collection suits you in your adapter. For example keep a reference to the ids and the albums which is the data that you're interested in displaying through the adapter.

private int[] ids;
private Album[] albums;

As you're passing the data (included in a map) to your adapter then you could extract that data and place it in the array containers so you can take advantage of the index. For example,

public MyAdapter(Map<Integer,Album> data){
        ids = new int[map.size()];
        albums = new Album[map.size()];
        int i = 0;
        for (Map.Entry<Integer,Album> e : map.entrySet()){
            ids[i] = e.getKey();
            albums[i++] = e.getValue();
        }
    }

Now that you have your arrays you can sort them also if you like and in case you want to grab the 3rd album and its id all you need to do is,

int id = ids[2];
Album album = albums[2];

Upvotes: 1

Related Questions