【问题标题】:How can i populate a RecyclerView with hashmap values?如何使用 hashmap 值填充 RecyclerView?
【发布时间】:2020-07-13 21:17:51
【问题描述】:

在我为此使用 ArrayList 之前,但由于重复的专辑问题(我在 API29 之前通过使用 DISTINCTGROUP BY 语句解决了),不再允许在查询中使用。

我在我的 RecyclerViews 适配器中得到了这样的值:myArrayList.get(position).getAlbum();

但现在我使用的是 HashMap,我怎样才能通过从适配器获得的位置获取值?

在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();
}

【问题讨论】:

    标签: java android android-recyclerview hashmap


    【解决方案1】:

    根据定义,HashMap 没有排序,那么SortedMap 怎么样? SortedMap 的一个实现是 TreeMap,它根据键(或 Comparator)对条目进行排序。

    我相信这适合你,因为你的地图有整数作为键。

    编辑: 您可以使用List 或适配器中适合您的任何集合。例如,保留对 id 和相册的引用,这是您有兴趣通过适配器显示的数据。

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

    当您将数据(包含在地图中)传递给适配器时,您可以提取该数据并将其放置在数组容器中,这样您就可以利用索引。例如,

    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();
            }
        }
    

    现在你有了你的数组,如果你愿意,你也可以对它们进行排序,如果你想获取第三张专辑和它的 ID,你需要做的就是,

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

    【讨论】:

    • 但是如何在 RecyclerView 中实现 SortedMap?我需要通过适配器位置获取值,例如。前 10 个项目的位置为 0-9,并且使用 Arraylist 我确实得到了类似 myArraylist.get(position).getAlbum(); 的值。不知道如何使用 SortedMap 实现相同的目标。
    • 我停止使用 ArrayList 的原因是因为我无法摆脱在使用 DISTINCT 和 GROUP BY 等 SQL 语句之前删除的重复专辑,但 Api 29 及更高版本停止支持这一点并且没有不再工作了。所以我想要实现的是在 RecyclerView 中获取 Hashmap 键和适配器位置之间的链接。
    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多