유튜브 리스트 출력 | Android Study

hoya·2021년 8월 15일
0

Android Study

목록 보기
5/19
post-thumbnail

😀 개요

우리는 평소에 필요한 정보를 찾을 때 유튜브를 꽤 많이 이용한다. 이 유튜브를 유튜브 공식 어플에서뿐 아니라 우리가 만드는 어플에서 활용할 수 있다면, 사용자는 이용하던 어플을 사용하다가 유튜브 어플을 다시 들어가는 피곤함을 덜 수 있을 것이다.

이번 포스팅의 목표는, 자전거의 부품을 수리할 때 참고할 수 있을만한 유튜브 리스트를 출력하는 것이다.

API는 각자 구글 클라우드 플랫폼에서 받아왔을 것이라고 가정, 레이아웃 영역 역시 포스팅에서 제외하며 코드 부분을 좀 더 자세하게 다뤄보도록 한다.


📑 기본적인 API 구조 학습

코딩에 앞서, 유튜브 API 구조에 관해 정말 간략하게, 필요한 부분만 찍어 먹어보도록 하자. 우리가 사용할 때 필요한 것은 우리가 원하는 검색값에 맞춰 원하는 동영상만 나오는 것, 즉 검색 부분이 필요하다.

이 사이트를 참고하도록 하자.

GET https://www.googleapis.com/youtube/v3/search

GET 방식으로 해당 사이트에 접근해 쿼리를 넣으면, 유튜브에서 우리가 원하는 결과를 출력할 것이다. 우리가 넣을 매개변수는 필수 매개변수인 part, key 선택 매개변수 q, type, maxResults 이다.

이렇게 매개변수를 넣고 위의 사이트에 대입하면 대략 이런 결과가 출력된다.

자, 기본적인 API 구조에 대해서 간략하게 알아보았으니, 안드로이드에서 이 유튜브 리스트를 출력해보도록 하자.


🙃 실습

📌 1. 통신

우선 안드로이드와 유튜브의 통신을 구현해야 한다. Retrofit2는 통신을 할 때 JSON 형태에 맞게 모델 클래스를 만들어 사용하기 때문에, JSON 형식의 파일을 다루기 매우 용이하다. 즉, JSON을 지지고 볶고 하는 파싱 없이 사용할 수 있다는 의미이다. 그런고로, 이번 포스팅에서는 Retrofit2 를 사용하도록 한다.

Retrofit2에 대한 학습이 부족하다면, Retrofit2를 간략하게 정리한 포스팅이 있으니, 한번 읽고 오는 것을 추천한다.

1-1. 모델 생성

위의 사진에서 보았던 결과값을 담을 모델을 생성한다. 모든 모델은 올리지 않고, 메인으로 처음에 출력되는 모델만 올리도록 하겠다.

package com.dongyang.android.boda.Repair.Model.GetAPI;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class YoutubeAPI {

    /**
     * kind : youtube#playlistItemListResponse
     * etag : "m2yskBQFythfE4irbTIeOgYYfBU/cz3MqGw9P-JEk5TDDLHOT5N_org"
     * nextPageToken : CAoQAA
     * pageInfo : {"totalResults":836,"resultsPerPage":10}
     * items : [{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/F5uKlv_00MDF9j4T7KQw5eiI56Y\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LmJ3OGdRakpxVU5Z","snippet":{"publishedAt":"2017-06-04T01:30:00.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Sikh Gurus & Nationalism: How Indian Nationalists Distorting the Imago of Sikh Guru Sahib","description":"Sikh political analyst and author Bhai Ajmer Singh visited Gurdwara Shaheed Bhai Mati Dass Ji, Nagpur on December 19, 2016 where he addressed the Sikh sangat. This is video recording of second speech of Bhai Ajmer Singh at Nagpur, delivered during evening diwan.\nIn this speech Bhai Ajmer Singh explained that how Indian nationalists are attempting of shrink and distort the imago of Sikh Guru Sahib to fulfil their ulterior interests.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/bw8gQjJqUNY/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/bw8gQjJqUNY/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/bw8gQjJqUNY/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/bw8gQjJqUNY/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/bw8gQjJqUNY/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":0,"resourceId":{"kind":"youtube#video","videoId":"bw8gQjJqUNY"}},"contentDetails":{"videoId":"bw8gQjJqUNY","videoPublishedAt":"2017-06-04T01:30:00.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/j4WLvxU3KncMCN6fr2l7BLFDwuI\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3Llc4aVBKNzBtUVdZ","snippet":{"publishedAt":"2017-05-22T02:00:01.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Special Talk with Advo. R S Bains About Capt. Amarinder's Disclosure on Fake Encounter of 21 Sikhs","description":"Punjab Chief Minister Capt. Amarinder Singh in a recent tweet disclosed a fact which amounts to clear admission of the fact that there were extra-judicial killings of the Sikhs in Punjab during 1980s-90.\n\nCapt. Amarinder disclosed that he was arranged surrender of 21 \u201cKhalistani militants\u201d but they were killed. Amarinder Singh\u2019s tweet also discloses that the policy of extra-judicial killings had sanction from the top of the Indian government.\n\nOn May 17, Punjab CM wrote in a tweet: \u201cI felt betrayed by then PM Chandra Shekhar after 21 Khalistani militants I arranged to surrender were killed. Never spoke to him after that\u201c.\n\nThe human rights activists in Punjab have all along been saying that Indian forces indulged into widespread, systematic and organised extra-judicial killings and fake encounters in Punjab during 1980s-90s.\n\nEarlier, in 2006, the then Punjab DGP SS Virk had admitted to have rehabilitated around 300 police cats (a term used for police informers who were used to identify the Sikh militants during 1980s-90s) under \u2018assumed\u2019 identities. Human rights groups say that these assumed identities were given to these police cats after they were shown as dead but in fact innocent Sikh youth were extra-judicially killed by the police to show that the police cats were dead.\n\nTalking to Sikh Siyasat News, Human Rights Lawyer and senior lawyer of Punjab and Haryana High Court Advocate Rajvinder Singh Bains said that Amarinder's statement is an official confirmation regarding the Indian state's policy of organised, systematic and widespread fake encounters in Punjab during 1980-90s.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/W8iPJ70mQWY/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/W8iPJ70mQWY/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/W8iPJ70mQWY/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/W8iPJ70mQWY/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/W8iPJ70mQWY/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":1,"resourceId":{"kind":"youtube#video","videoId":"W8iPJ70mQWY"}},"contentDetails":{"videoId":"W8iPJ70mQWY","videoPublishedAt":"2017-05-22T02:00:01.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/_yxbhuN_-tBz75GxSLLuV9QEigg\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LlNkZ0ZRZnVtSTQw","snippet":{"publishedAt":"2017-05-25T13:30:00.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Samvad at Sri Hargobindpur (1): Introductory Speech by Bhai Mandhir Singh","description":"Samvad, a discussion forum, held a discussion on \"Panth-Punjab: Present Situation and Solutions\" at Sri Hargobindpur on March 19, 2017. This is video recording of introductory speech by Bhai Mandhir Singh during this Samvad.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/SdgFQfumI40/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/SdgFQfumI40/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/SdgFQfumI40/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/SdgFQfumI40/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/SdgFQfumI40/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":2,"resourceId":{"kind":"youtube#video","videoId":"SdgFQfumI40"}},"contentDetails":{"videoId":"SdgFQfumI40","videoPublishedAt":"2017-05-25T13:30:00.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/lrCrKIE5EI1tHjdyTycs4ggLPP4\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3Ll9wa0ZFbnBFNjdr","snippet":{"publishedAt":"2017-05-25T12:00:04.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Samvad at Sri Hargobindpur (2): On Approach Towards History - by Bhai Ajmer Singh","description":"Samvad, a discussion forum, held a discussion on \"Panth-Punjab: Present Situation and Solutions\" at Sri Hargobindpur on March 19, 2017. During this Samvad Bhai Ajmer Singh shared his views on 'Approach towards the History' (ਇਤਿਹਾਸ ਪ੍ਰਤੀ ਪਹੁੰਚ). This is video recording of speech of Bhai Ajmer Singh.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/_pkFEnpE67k/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/_pkFEnpE67k/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/_pkFEnpE67k/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/_pkFEnpE67k/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/_pkFEnpE67k/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":3,"resourceId":{"kind":"youtube#video","videoId":"_pkFEnpE67k"}},"contentDetails":{"videoId":"_pkFEnpE67k","videoPublishedAt":"2017-05-25T12:00:04.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/Fzwoy0pXFKPMwtey-I5fOAFTKbs\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LnpFX0xZckU5elZn","snippet":{"publishedAt":"2017-05-25T11:00:04.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Samvad at Sri Hargobindpur (3): Panth-Punjab: Present Situation and Solutions - Open Discussion","description":"Samvad, a discussion forum, held a discussion on \"Panth-Punjab: Present Situation and Solutions\" at Sri Hargobindpur on March 19, 2017. This is video recording of open discussion session.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/zE_LYrE9zVg/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/zE_LYrE9zVg/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/zE_LYrE9zVg/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/zE_LYrE9zVg/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/zE_LYrE9zVg/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":4,"resourceId":{"kind":"youtube#video","videoId":"zE_LYrE9zVg"}},"contentDetails":{"videoId":"zE_LYrE9zVg","videoPublishedAt":"2017-05-25T11:00:04.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/Y-x-JFIV6raR9i0HfKgdQNejuos\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LjJ6bmZCREFIWHNj","snippet":{"publishedAt":"2017-05-18T01:30:01.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Bhai Ajmer Singh' Nagpur Speech: How to Adopt Balance Approach on Issues Concerning Sikh Panth","description":"Sikh Political Analyst and author Bhai Ajmer Singh address the Sikh sangat at Gurdwara Shaheed Bhai Mati Dass Ji (Nagpur) on December 19, 2016. He urged that Sikhs should adopt a balanced approach towards issues concerning the Sikh panth and cited historical references that Guru Sahib have shown us the path following which we can identify and adopt the right approach. \n\nThis is video recording of speech delivered by Bhai Ajmer Singh at Gurdwara Shaheed Bhai Mati Dass Ji (Nagpur) in morning diwan on December 16, 2016.\n\nSikh Siyasat is thankful to the organizers of the event for providing the  video recording and their permissions to exclusively share it with our viewers.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/2znfBDAHXsc/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/2znfBDAHXsc/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/2znfBDAHXsc/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/2znfBDAHXsc/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/2znfBDAHXsc/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":5,"resourceId":{"kind":"youtube#video","videoId":"2znfBDAHXsc"}},"contentDetails":{"videoId":"2znfBDAHXsc","videoPublishedAt":"2017-05-18T01:30:01.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/zPgoflJ6jdjv0FIGiSpA3l0txX8\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LmE3SGZRZDNBTllj","snippet":{"publishedAt":"2017-05-13T03:13:59.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Analysis of Aam Aadmi Party's Crisis: An Unconventional Viewpoint by S. Ajmer Singh","description":"Aam Aadmi Party is facing a deep crisis. It seems that the party is caught in existential crisis after it failed to win assembly elections in Punjab. Sikh political analyst Bhai Ajmer Singh has presented his viewpoint and analysis about AAP's present crisis in this video.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/a7HfQd3ANYc/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/a7HfQd3ANYc/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/a7HfQd3ANYc/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/a7HfQd3ANYc/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/a7HfQd3ANYc/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":6,"resourceId":{"kind":"youtube#video","videoId":"a7HfQd3ANYc"}},"contentDetails":{"videoId":"a7HfQd3ANYc","videoPublishedAt":"2017-05-13T03:13:59.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/NS9Z1y-yPAbAyGIp8NO_4dmKpH0\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LmF6dUJ4MWhFQUFz","snippet":{"publishedAt":"2017-04-27T02:30:00.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Panth-Punjab: Contemporary Situation and Solution (1) - Dr. Sewak Singh at Talwandi Sabo Samvad","description":"Samvad, a discussion forum, held a discussion forum on \"Panth-Punjab: Contemporary Situation and Solution\" at Talwandi Sabo (Bathinda) on March 05, 2017.\nSikh author Bhai Ajmer Singh and Dr. Sewak Singh shared their views during first half of the discussion. The second part of the discussion comprised a question and answers session. This is video recording of initial speech of Dr. Sewak Singh during this samvad.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/azuBx1hEAAs/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/azuBx1hEAAs/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/azuBx1hEAAs/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/azuBx1hEAAs/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/azuBx1hEAAs/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":7,"resourceId":{"kind":"youtube#video","videoId":"azuBx1hEAAs"}},"contentDetails":{"videoId":"azuBx1hEAAs","videoPublishedAt":"2017-04-27T02:30:00.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/PGScVcoXMkbcd-1ub6M93ZYKZ3Q\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LlVVNnBudXR6NXl3","snippet":{"publishedAt":"2017-04-27T02:00:00.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Panth-Punjab: Contemporary Situation and Solution (2) - Bhai Ajmer Singh at Talwandi Sabo Samvad","description":"Samvad, a discussion forum, held a discussion forum on \"Panth-Punjab: Contemporary Situation and Solution\" at Talwandi Sabo (Bathinda) on March 05, 2017.\nSikh author Bhai Ajmer Singh and Dr. Sewak Singh shared their views during first half of the discussion. The second part of the discussion comprised a question and answers session. This is video recording of initial speech of Bhai Ajmer Singh during this samvad.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/UU6pnutz5yw/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/UU6pnutz5yw/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/UU6pnutz5yw/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/UU6pnutz5yw/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/UU6pnutz5yw/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":8,"resourceId":{"kind":"youtube#video","videoId":"UU6pnutz5yw"}},"contentDetails":{"videoId":"UU6pnutz5yw","videoPublishedAt":"2017-04-27T02:00:00.000Z"}},{"kind":"youtube#playlistItem","etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/5QIWzobbbAMwhpL7Re79CEo5ExM\"","id":"VVVsc3BPendQQ1RzeTB2UWRfZjNGWFp3LjhKMHo1TjFoZFRJ","snippet":{"publishedAt":"2017-04-27T01:30:00.000Z","channelId":"UClspOzwPCTsy0vQd_f3FXZw","title":"Panth-Punjab: Contemporary Situation and Solution (3) - Discussion During Samvad at Talwandi Sabo","description":"Samvad, a discussion forum, held a discussion forum on \"Panth-Punjab: Contemporary Situation and Solution\" at Talwandi Sabo (Bathinda) on March 05, 2017.\nSikh author Bhai Ajmer Singh and Dr. Sewak Singh shared their views during first half of the discussion. The second part of the discussion comprised a question and answers session. This is video recording of second part of this discussion.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/8J0z5N1hdTI/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/8J0z5N1hdTI/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/8J0z5N1hdTI/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/8J0z5N1hdTI/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/8J0z5N1hdTI/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"SikhSiyasat","playlistId":"UUlspOzwPCTsy0vQd_f3FXZw","position":9,"resourceId":{"kind":"youtube#video","videoId":"8J0z5N1hdTI"}},"contentDetails":{"videoId":"8J0z5N1hdTI","videoPublishedAt":"2017-04-27T01:30:00.000Z"}}]
     */

    @SerializedName("kind")
    private String kind;
    @SerializedName("etag")
    private String etag;
    @SerializedName("nextPageToken")
    private String nextPageToken;
    @SerializedName("regionCode")
    private String regionCode;
    @SerializedName("pageInfo")
    private PageInfoBean pageInfo;
    @SerializedName("items")
    private List<ItemsBean> items;

    public String getKind() {
        return kind;
    }

    public void setKind(String kind) {
        this.kind = kind;
    }

    public String getEtag() {
        return etag;
    }

    public void setEtag(String etag) {
        this.etag = etag;
    }

    public String getNextPageToken() {
        return nextPageToken;
    }

    public void setNextPageToken(String nextPageToken) {
        this.nextPageToken = nextPageToken;
    }

    public PageInfoBean getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(PageInfoBean pageInfo) {
        this.pageInfo = pageInfo;
    }

    public String getRegionCode() {
        return regionCode;
    }

    public void setRegionCode(String regionCode) {
        this.regionCode = regionCode;
    }


    public List<ItemsBean> getItems() {
        return items;
    }

    public void setItems(List<ItemsBean> items) {
        this.items = items;
    }

    public static class PageInfoBean {
        /**
         * totalResults : 836
         * resultsPerPage : 10
         */

        @SerializedName("totalResults")
        private int totalResults;
        @SerializedName("resultsPerPage")
        private int resultsPerPage;

        public int getTotalResults() {
            return totalResults;
        }

        public void setTotalResults(int totalResults) {
            this.totalResults = totalResults;
        }

        public int getResultsPerPage() {
            return resultsPerPage;
        }

        public void setResultsPerPage(int resultsPerPage) {
            this.resultsPerPage = resultsPerPage;
        }
    }
}

이런 식으로, 데이터를 담을 모델들을 생성해주면 된다. 모델 생성에 어려움을 겪는다면 jsonshcema2pojo 라는 사이트를 추천한다. 위에서 나온 JSON 값을 그대로 복사하여 붙여넣기 하면 이렇게 모델을 생성해준다.


1-2. 인터페이스 설정

public interface YoutubeService {

    String YOUTUBE_URL = "https://www.googleapis.com";

    @GET("/youtube/v3/search")
    Call<YoutubeAPI> getList(
            @Query("key") String key,
            @Query("part") String part,
            @Query("q") String q,
            @Query("type") String type,
            @Query("maxResults") int maxResults
            );
}

위에서 GET 방식으로 유튜브로 요청을 달라고 했으니, 그에 맞게 매개변수들을 넣어 요청을 해주면 된다.


1-3. 실제 연결

public class YoutubeActivity extends AppCompatActivity {

    private String MY_KEY = "YOUR_KEY"; // API KEY
    private String Q; // 유튜브 검색값
    private int MAX_RESULTS = 30; // 받아올 유튜브 리스트의 최대값


    private RecyclerView y_recyclerView; // 리사이클러뷰
    private YoutubeAdapter y_adapter; // 어댑터
    private List<Youtube> y_datas = new ArrayList<>(); // 출력 데이터를 담을 배열


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_youtube);

        Q = "자전거 타이어 고치는 방법";

        // 리사이클러뷰 사이즈 지정 및 레이아웃 설정
        y_recyclerView = findViewById(R.id.youtube_recyclerView);
        y_recyclerView.setHasFixedSize(true);
        y_recyclerView.addItemDecoration(new DividerItemDecoration(YoutubeActivity.this, DividerItemDecoration.VERTICAL)); // 구분선 지정
        y_recyclerView.setLayoutManager(new LinearLayoutManager(YoutubeActivity.this));

        // 툴바 설정
        Toolbar toolbar = findViewById(R.id.youtube_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false); // 타이틀 제거
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 뒤로가기 활성화
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back); // 뒤로가기 아이콘 활성화

        Gson gson = new GsonBuilder().setLenient().create(); // JSON 응답을 객체로 변환하기 위해 필요

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YoutubeService.YOUTUBE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson)) // gson 부여
                .build();

        YoutubeService retrofitAPI = retrofit.create(YoutubeService.class); // 유튜브 인터페이스와 연결

        retrofitAPI.getList(MY_KEY,"snippet", Q, "video", MAX_RESULTS).enqueue(new Callback<YoutubeAPI>() {
                        // API KEY, snippet 영역을 받아옴, 검색값, 비디오만, MAX_RESULT 값 만큼 유튜브 서버에 요청
            @Override
            public void onResponse(Call<YoutubeAPI> call, Response<YoutubeAPI> response) {
                if (response.isSuccessful()) { // 성공적으로 받아왔을 때
                    Log.d("YOUTUBE", "Response");
                    YoutubeAPI data = response.body(); // 받아온 데이터를 변수에 저장

                    List<ItemsBean> youtubeList = data.getItems(); // 변수에서 아이템 리스트들을 받아온다.

                    for(int i = 0; i < youtubeList.size(); i++) {
                        String title = youtubeList.get(i).getSnippet().getTitle(); // 타이틀 파싱
                        String url =  youtubeList.get(i).getSnippet().getThumbnails().getMedium().getUrl(); // 썸네일 url 파싱

                        y_datas.add(new Youtube(title, url)); // 필요한 데이터만 추가
                        y_adapter = new YoutubeAdapter(YoutubeActivity.this, y_datas); // 어댑터 설정
                        y_recyclerView.setAdapter(y_adapter);
                    }
                }
            }

            @Override
            public void onFailure(Call<YoutubeAPI> call, Throwable t) {
                Log.d("YOUTUBE", "Error");
                t.printStackTrace();
            }
        });


    }

📌 2. 리사이클러뷰 설정

이제 데이터는 모두 담아왔으니 리스트에 담아 사용자에게 보여주면 된다. 어댑터 부분을 살펴보도록 하자. 자잘한 부분은 이전에 RecyclerView를 설명했던 포스팅이 있으니 생략했고, 실제 뷰에 담는 ViewHolder 영역만 주석을 작성했다.

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

    private Context context;
    private List<Youtube> datas = new ArrayList<>();

    public YoutubeAdapter(Context context, List<Youtube> datas) {
        this.context = context;
        this.datas = datas;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_youtube, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bind(context, datas, position);
    }

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


    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        ImageView thumbnail;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            title = itemView.findViewById(R.id.youtube_title);
            thumbnail = itemView.findViewById(R.id.youtube_thumbnail);
        }

        private void bind(Context context, List<Youtube> datas, int position) {
            title.setText(datas.get(position).getTitle()); // 해당 포지션에서 제목을 받아옴
            String url = datas.get(position).getUrl(); // 해당 포지션에서 썸네일 url을 받아옴
            Glide.with(context).load(url).into(thumbnail); // url -> 사진으로 변경 후 이미지뷰에 설정

            itemView.setOnClickListener(new View.OnClickListener() { // 리스트를 눌렀을 때 액션 설정(해당 유튜브 동영상이 나오게 설정해야 함)
                @Override
                public void onClick(View view) {
                    Toast.makeText(context, "클릭하였음.", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

}

유튜브에서는 url 형식으로 썸네일 이미지를 전달하기 때문에, Glide 를 이용하여 url -> 이미지로 변환하였다.


🤗 결과

성공적으로 유튜브 리스트가 출력된 모습을 확인할 수 있다. 하루 할당량이 만 개로 제한되어 있으니, 주의하며 API를 활용해야 한다.


참고 및 출처

Retrofit2 사용법
YouTube DATA API
Glide 로 이미지 Load하기
YouTube API를 이용하여 비디오 리스트 불러오기
YouTube Model 생성

profile
즐겁게 하자 🤭

3개의 댓글

comment-user-thumbnail
2022년 8월 23일

ItemBean 클래스는 GET내용을 기반으로 클래스를 만드신 건가요?

1개의 답글