Android

How to add youtube playlist to your android app tutorial

Here is the full source code: The complete source code is here: Click here to download the full working code!!

First thing you will want to do is create a new blank activity project in android studio.

Now open up activity_main.xml and replace the code in there with the following:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >


</FrameLayout>


This FrameLayout will hold our fragment that holds our Youtube playlist.

Now create a new class with a superclass of Fragment. I chose to use the support fragment.

Also we need to create the layout for the youtube playlist. We are going to use the RecyclerView to display the playlist in a list, using card views.

Create a new layout resource file:

cm_yt_playlist_recycler.xml

<android.support.v7.widget.RecyclerView
    android:id="@+id/yt_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

We also need to create a new layout for each row which will be a CardView that shows a thumbnail and description of the video:

cm_yt_list_items.xml

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="91dp"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    android:elevation="3dp"
    card_view:cardCornerRadius="0dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <ImageView
            android:layout_width="76dp"
            android:layout_height="match_parent"

            android:id="@+id/imageView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="12dp"
            android:layout_marginStart="12dp"
            android:layout_alignParentTop="true"
            android:src="@drawable/bt_about" />

        <TextView
            android:text="TextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/name"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/imageView"
            android:layout_toEndOf="@+id/imageView"
            android:layout_marginLeft="50dp"
            android:layout_marginStart="50dp" />

    </RelativeLayout>


</android.support.v7.widget.CardView>


For RecyclerView and CardView to work we will need to add them as dependencies in gradle.

// RecyclerView
compile 'com.android.support:recyclerview-v7:24.3.+'
// CardView
compile 'com.android.support:cardview-v7:24.3.+'
//glide
compile 'com.github.bumptech.glide:glide:3.7.0

Notice I also added glide which will load our thumbnails into each CardView.

Lets open up MainActivity.java and load our fragment:

In the onCreate method, under setContentView(R.layout.activity_main); , add this:

FragmentManager fragmentManager = getSupportFragmentManager();
Fragment start_frag = fragmentManager.findFragmentById(R.id.fragment_container);
if(start_frag == null) {
start_frag = new CM_youtubePlaylist();
fragmentManager.beginTransaction().add(R.id.fragment_container, start_frag).commit();
}


Now we need to get a youtube browser api key from the google developer console:
https://console.developers.google.com

Now do not click restrict key and click done.

Copy your new api key and save it somewhere safe.

Now create a class called Videos.java that will hold our info of the videos in a playlist.

public class Videos { 
 private String title;
 private String thumbnail_url;
 private String videoID;   

    public Videos(String title, Bitmap t, String thumbnail_url, String videoid) {
        this.title = title;
        this.thumbnail_url= thumbnail_url;
        this.videoID = videoid;
    }

    public String getTitle() {
        return title;
    }
    public String getThumbnailUrl() {
        return thumbnail_url;
    }
    public String getVideoID() {
        return videoID;
    }


}

Next download the youtube jar for android:
https://developers.google.com/youtube/android/player/downloads/

Open up your project in a file explorer on your machine, and drag the jar file to the libs folder of your project. DO NOT drag and drop it into android studio. I believe you can also add it as an file dependency in android studio.

Ok, it’s time to work on the fragment that will show our videos using RecyclerView. Here we will load the thumbnails using the Glide library. We will also load the description of the video and add an onclicklistener for the row/cardview.

Create a class called YT_recycler_adapter and add this code to it:

private List videoList;
String key;
Activity activity;
private int REQ_PLAYER_CODE  = 1;
int cornerRadius;
int cardColor;
int textColor;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView name;
    public ImageView imageView;



    public MyViewHolder(View view) {
        super(view);


        imageView = (ImageView)view.findViewById(R.id.imageView) ;


        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Videos video = videoList.get(getAdapterPosition());

                Intent videoIntent = YouTubeStandalonePlayer.createVideoIntent(activity, key, video.getVideoID(), 0, true, false);

                activity.startActivityForResult(videoIntent, REQ_PLAYER_CODE);


            }
        });


        CardView cardView = (CardView) view.findViewById(R.id.card_view);
        cardView.setCardBackgroundColor(cardColor);
        cardView.setRadius(cornerRadius);


        name = (TextView) view.findViewById(R.id.name);
        name.setTextColor(textColor);
        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });



    }
}




public YT_recycler_adapter(List videoList, String yt_key, Activity activity, int cornerRadius, int cardColor, int textColor) {
    this.activity  = activity;
    this.key = yt_key;
    this.videoList = videoList;
    this.cornerRadius = cornerRadius;
    this.cardColor = cardColor;
    this.textColor = textColor;

}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.cm_yt_list_items, parent, false);


    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Videos video = videoList.get(position);
    holder.name.setText(video.getTitle());


    Glide.with(activity)
            .load(video.getThumbnailUrl() ) // Uri of the picture
            .into(holder.imageView);




}

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

Next we will make https requests to the youtube api and add them to video objects, to be added to a list and passed to the adapter for viewing. Please edit the code to include your own playlist id and browser api key. Playlist ids are the characters after “PL” in some youtube urls.
Now open up CM_youtubePlaylist.java and add this code:

package com.chriscoffee.youtubeplaylist.youtubeplaylist;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by christophercoffee on 12/17/16.
 */

public class CM_youtubePlaylist extends Fragment {


    List<Videos> displaylistArray = new ArrayList<Videos>();
    private RecyclerView mVideoRecyclerView;
    private YT_recycler_adapter mVideoAdapter;
    Context context;
    private String playlist_id;
    private String browserKey;
    String loadMsg;
    String loadTitle;


    //onCreateView...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){


        //show life-cycle event in LogCat console...
       context = getActivity().getApplicationContext();
        View thisScreensView = inflater.inflate(R.layout.cm_yt_playlist_recycler, container, false);








        //show a long toast so user knows this screen is blank intentionally...
        //showToast("This screen is blank intentionally. See CM_anWatchList.java to see how little is required to launch a simple plugin.", "long");
        playlist_id = "yourPlaylistId";
        int videoTxtColor = Color.parseColor("#000000");
        loadTitle = "Loading...";
        loadMsg = "Loading your videos...";
        browserKey = "yourBrowserKey";
        int cornerRadius = 5;
        int cardColor = Color.parseColor("#FFFFFF");
        int recyclerColor = Color.parseColor("#ff0000");


        mVideoRecyclerView = (RecyclerView) thisScreensView.findViewById(R.id.yt_recycler_view);
        mVideoRecyclerView.setBackgroundColor(recyclerColor);
        mVideoRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mVideoAdapter = new YT_recycler_adapter(displaylistArray, browserKey, getActivity(), cornerRadius, cardColor, videoTxtColor);
        mVideoRecyclerView.setAdapter(mVideoAdapter);

        new TheTask().execute();

        mVideoAdapter.notifyDataSetChanged();

        //return the layout file as the view for this screen..
        return thisScreensView;


    }//onCreateView...


    private class TheTask extends AsyncTask<Void,Void,Void>
    {

        Videos displaylist;
        private ProgressDialog dialog;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            dialog = new ProgressDialog(getActivity());
            dialog.setTitle(loadTitle);
            dialog.setMessage(loadMsg);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            try
            {

                String url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=" + playlist_id+ "&key=" + browserKey + "&maxResults=50";

                String response = getUrlString(url);

                JSONObject json = new JSONObject(response.toString());

                JSONArray jsonArray = json.getJSONArray("items");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);


                    JSONObject video = jsonObject.getJSONObject("snippet").getJSONObject("resourceId");
                    String title = jsonObject.getJSONObject("snippet").getString("title");

                    String id = video.getString("videoId");

                    String thumbUrl = jsonObject.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url");


                    displaylist = new Videos(title, thumbUrl ,id);
                    displaylistArray.add(displaylist);
                }


            }
            catch(Exception e1)
            {
                e1.printStackTrace();
            }


            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            mVideoAdapter.notifyDataSetChanged();

            if (dialog.isShowing()) {
                dialog.dismiss();
            }

        }

    }



    private byte[] getUrlBytes(String urlSpec) throws IOException {
        URL url = new URL(urlSpec);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = connection.getInputStream();
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException(connection.getResponseMessage() +
                        ": with " +
                        urlSpec);
            }
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            out.close();
            return out.toByteArray();
        } finally {
            connection.disconnect();
        }
    }
    private String getUrlString(String urlSpec) throws IOException {
        return new String(getUrlBytes(urlSpec));
    }
}

Lastly open up AndroidManifest.xml and add the internet permission, so we can make https requests. Add the permission outside of the application tag.


The complete source code is here: Click here to download the full working code!!

4 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *