【问题标题】:Sorting YouTube data with JSON in RecyclerView在 RecyclerView 中使用 JSON 对 YouTube 数据进行排序
【发布时间】:2021-02-06 20:54:40
【问题描述】:

我正在使用 YouTube 数据 API 并在 RecyclerView 中使用 JSON Retrofit 获取数据。数据包含来自频道的视频列表,其中还包括直播视频。

频道的网址是:

https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCJekW1Vj5fCVEGdye_mBN6Q&maxResults=50&order=date&key=[YOUR_API_KEY] .

我正在尝试对 RecyclerView 中的数据进行排序,以使实时视频位于列表顶部,其余视频则根据日期进行排序。 RecyclerView的适配器如下:

public class AdapterHome extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private List<VideoYT> videoList;

    public
    AdapterHome(Context context, List<VideoYT> videoList) {
        this.context = context;
        this.videoList = videoList;
    }

    class YoutubeHolder extends RecyclerView.ViewHolder {

        ImageView thumbnail;
        TextView judul, tanggal;

        public YoutubeHolder(@NonNull View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.iv_thumbnail);
            judul = itemView.findViewById(R.id.tv_judul);
            tanggal = itemView.findViewById(R.id.tv_tglUpdate);
        }

        public void setData(final VideoYT data) {
            final String getJudul = data.getSnippet().getTitle();
            String getTgl = data.getSnippet().getPublishedAt();
            String getThumb = data.getSnippet().getThumbnails().getMedium().getUrl();

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(context, YTPlayerActivity.class);
                    i.putExtra("video_id", data.getId().getVideoId());
                    i.putExtra("video_title", getJudul);
                    context.startActivity(i);
                }
            });

            judul.setText(getJudul);
            tanggal.setText(getTgl);
            Picasso.get()
                    .load(getThumb)
                   // .placeholder(R.mipmap.ic_gujrati)
                    .fit()
                    .centerCrop()
                    .into(thumbnail, new Callback() {
                        @Override
                        public void onSuccess() {
                            Log.d(TAG, "Thumbnail berhasil ditampilkan");
                        }

                        @Override
                        public void onError(Exception e) {
                            Log.e(TAG, "Thumbnail error: ", e);
                        }
                    });
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.row_item_home, parent, false);
        return new YoutubeHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        VideoYT videoYT = videoList.get(position);
        YoutubeHolder yth = (YoutubeHolder) holder;
        yth.setData(videoYT);
    }

    @Override
    public int getItemCount() {
        return videoList.size();
    }
}

默认排序顺序没有为此提供任何选项。 有人可以指导我吗?

本次搜索的JSON数据格式如下:

    {
      "kind": "youtube#searchResult",
      "etag": "BARItyEvlwxiMQCYVni5-wa94N0",
      "id": {
        "kind": "youtube#video",
        "videoId": "C51KWXknpd8"
      },
      "snippet": {
        "publishedAt": "2020-10-23T11:33:46Z",
        "channelId": "UCJekW1Vj5fCVEGdye_mBN6Q",
        "title": "SAMAA News Live | Samaa TV Live | 24/7 Pakistan News Live Headlines, Bulletins &amp; Press Conferences",
        "description": "samaalive #pakistannewslive #livenews LIVE STREAM SAMAA TV 24/7 | live streaming on YouTube | Headlines , Bulletins, Special & Exclusive Coverage Stay ...",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/C51KWXknpd8/default_live.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/C51KWXknpd8/mqdefault_live.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/C51KWXknpd8/hqdefault_live.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "SAMAA TV",
        **"liveBroadcastContent": "live",**
        "publishTime": "2020-10-23T11:33:46Z"
      }
    },
    {
      "kind": "youtube#searchResult",
      "etag": "3qQo96hAKuvzR1yqmOX2RRwm0fg",
      "id": {
        "kind": "youtube#video",
        "videoId": "JSUmX2wgwwk"
      },
      "snippet": {
        "publishedAt": "2020-10-23T11:20:53Z",
        "channelId": "UCJekW1Vj5fCVEGdye_mBN6Q",
        "title": "Samaa Headlines 4pm | Muhammad Zubair Jhoot bolne ke mahir hain - Shibili Faraz",
        "description": "samaanewslive #breakingnews #pakistannewslive Stay up-to-date on the major news making headlines across Pakistan on SAMAA TV's top of the hour ...",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/JSUmX2wgwwk/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/JSUmX2wgwwk/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/JSUmX2wgwwk/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "SAMAA TV",
        "liveBroadcastContent": "none",
        "publishTime": "2020-10-23T11:20:53Z"
      }
    },

【问题讨论】:

    标签: android android-recyclerview youtube-data-api


    【解决方案1】:

    您的问题归结为 VideoYT 类有一个自定义比较器(例如,在 AdapterHome 类本身中定义):

    public static Comparator<VideoYT> myComparator = 
        new Comparator<VideoYT>() {
            @Override
            public int compare(VideoYT a, VideoYT b) {
                boolean aLive = a.getSnippet().getLiveBroadcastContent() == "live";
                boolean bLive = b.getSnippet().getLiveBroadcastContent() == "live";
                if (aLive == bLive)
                   return b.getSnippet().getPublishedAt().compareTo(
                          a.getSnippet().getPublishedAt());
                else
                   return aLive ? -1 : +1;
            }
        };
    

    然后在AdapterHome的构造函数中使用这个比较器对videoList进行排序:

    public
    AdapterHome(Context context, List<VideoYT> videoList) {
        this.context = context;
        Collections.sort(videoList, myComparator);         
        this.videoList = videoList;
    }
    

    根据您的程序的更广泛上下文(上面的示例代码未显示),您可能还需要(想要?)在该构造函数中不修改videoList。然后,不要对videoList 本身进行排序,而是对其进行复制并对该副本进行排序:

    public
    AdapterHome(Context context, List<VideoYT> videoList) {
        this.context = context;
        this.videoList = new ArrayList<>(videoList);
        Collections.sort(this.videoList, myComparator);
    }
    

    【讨论】:

    • 你能解释一下在适配器中添加最后一部分(collection.sort)的位置吗?
    • 已经说过:在类AdapterHome的构造函数中。请参阅上面我编辑的答案。
    • 谢谢..但它现在没有显示任何内容。黑屏没有项目
    • 您选择了两种选择中的哪一种?
    • 第二个。让我也试试第一个
    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多