Introduction
Youtube is an awesome platform to share and watch videos. In this article we will learn about how to integrate youtube channel in Android App. We will use Youtube Android Player API to show videos in YoutubePlayerView. Now we will go through step by step of this tutorial and integrate Youtube channel in Android.
Steps
1. Find Youtube Channel ID: Go to any Youtube’s channel homepage and copy the URL of that channel. Suppose if we copy URL of Narendra Modi’s channel the URL will look like this link which is given below. The last words after channel/ is channel id.
URL: https://www.youtube.com/channel/UC1NF71EwP41VdjAU1iXdLkw
Channel Id: UC1NF71EwP41VdjAU1iXdLkw
2. Generate SHA1 key: When you signup for Youtube player API on Google Developer console you need to generate SHA1 key. For this follow these steps.
- Go to your Android Project and click on Gradle icon.
- Click on YourProjectName(root) after that if nothing is showing click on refresh icon.
- Now go to Tasks -> android -> signingReport. You will find SHA1 key.
3. Get API Key for Youtube Data API v3: Go to Google Developer Console and click on select a project you can choose existing project or create a new project for Youtube integration.
3.2 Search for Youtube Data API v3 choose this API and enable it. Now you will navigate to project dashboard.
3.3 Click on Credentials Now create credentials and copy your API key and save it. You can restrict key by choosing according to your usage and paste the SHA1 key that we generated in step 2 and save it. We are selecting none, however it is always recommended that to use restriction.
4.Get Channel video list in JSON format: Now go to the Youtube Data API docs and scroll down you will find Authorize and Execute button for sake of simplicity we execute data in Load in APIs Explorer and we navigate to another page.
4.2 There are many parameters but only part parameter is mandatory and now put channel id in channelId text field that we got in first step. Hit Authorize and Execute button we will get videos list and descriptions of the channel in JSON. Copy your URL that we are getting from GET Request. You can run this URL in browser as well by replacing {YOUR_API_KEY} with your API key.
Android Integration Part
We will use Volley library to parse json data and populate into a listview. We have to add it in our build.gradle file of App.
compile 'com.mcxiaoke.volley:library:1.0.19'
Now we need to add YoutubeAndroidPlayerApi.jar in Android Studio project.
ownload the YoutubeAndroidPlayerApi.jar file and copy this into your libs folder of Android project. If the folder does not exist create a libs folder.
5.Create ChannelActivity Activity: I named it as a activity_channel. In this activity we are using ListView to show you tube videos in a list. The XML code of this file is given below.
="1.0"="utf-8"
<LinearLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android" rel="nofollow">http://schemas.android.com/apk/res/android</a>"
xmlns:app="<a href="http://schemas.android.com/apk/res-auto" rel="nofollow">http://schemas.android.com/apk/res-auto</a>"
xmlns:tools="<a href="http://schemas.android.com/tools" rel="nofollow">http://schemas.android.com/tools</a>"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/youtube_fragment"
tools:context="com.techiesatish.youtubeintegration.ChannelActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/videoList">
</ListView>
</LinearLayout>
5.2 ChannelActivity.java: we are parsing JSON data and using a custom adapter to supply data in a ListView. May be, you will get some error due to not getting classes just leave that and follow other next steps to create classes.
package com.techiesatish.youtubeintegration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ChannelActivity extends AppCompatActivity {
ListView lvVideo;
ArrayList<VideoDetails> videoDetailsArrayList;
CustomListAdapter customListAdapter;
String searchName;
String TAG="ChannelActivity";
String URL="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC9CYT9gSNLevX5ey2_6CK0Q&maxResults=25&key={Your API KEI}";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel);
lvVideo=(ListView)findViewById(R.id.videoList);
videoDetailsArrayList=new ArrayList<>();
customListAdapter=new CustomListAdapter(ChannelActivity.this,videoDetailsArrayList);
showVideo();
}
private void showVideo() {
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
JSONObject jsonsnippet= jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectdefault = jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");
VideoDetails videoDetails=new VideoDetails();
String videoid=jsonVideoId.getString("videoId");
Log.e(TAG," New Video Id" +videoid);
videoDetails.setURL(jsonObjectdefault.getString("url"));
videoDetails.setVideoName(jsonsnippet.getString("title"));
videoDetails.setVideoDesc(jsonsnippet.getString("description"));
videoDetails.setVideoId(videoid);
videoDetailsArrayList.add(videoDetails);
}
lvVideo.setAdapter(customListAdapter);
customListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
6. Create a CustomListAdapter class: This class extending BaseAdapter and populating data in a ListView. The code is given below.
package com.techiesatish.youtubeintegration;
import android.support.v4.app.FragmentManager;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private LayoutInflater inflater;
ArrayList<VideoDetails> singletons;
public CustomListAdapter(Activity activity, ArrayList<VideoDetails> singletons) {
this.activity = activity;
this.singletons = singletons;
}
public int getCount() {
return this.singletons.size();
}
public Object getItem(int i) {
return this.singletons.get(i);
}
public long getItemId(int i) {
return (long) i;
}
public View getView(int i, View convertView, ViewGroup viewGroup) {
if (this.inflater == null) {
this.inflater = (LayoutInflater) this.activity.getLayoutInflater();
}
if (convertView == null) {
convertView = this.inflater.inflate(R.layout.videolist, null);
}
if (this.imageLoader == null) {
this.imageLoader = AppController.getInstance().getImageLoader();
}
NetworkImageView networkImageView = (NetworkImageView) convertView.findViewById(R.id.video_image);
final TextView imgtitle = (TextView) convertView.findViewById(R.id.video_title);
final TextView imgdesc = (TextView) convertView.findViewById(R.id.video_descriptio);
final TextView tvURL=(TextView)convertView.findViewById(R.id.tv_url);
final TextView tvVideoID=(TextView)convertView.findViewById(R.id.tv_videoId);
((LinearLayout) convertView.findViewById(R.id.asser)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(view.getContext(), VideoActivity.class);
intent.putExtra("videoId",tvVideoID.getText().toString());
view.getContext().startActivity(intent);
}
});
VideoDetails singleton = (VideoDetails) this.singletons.get(i);
networkImageView.setImageUrl(singleton.getURL(), this.imageLoader);
tvVideoID.setText(singleton.getVideoId());
imgtitle.setText(singleton.getVideoName());
imgdesc.setText(singleton.getVideoDesc());
return convertView;
}
}
7. Create an AppController class: In this class we are creating an AppController
class which is extending Application. We also need to define it in AndroidManifest file.
package com.techiesatish.youtubeintegration;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private static AppController mInstance;
private ImageLoader mImageLoader;
private RequestQueue mRequestQueue;
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
AppController appController;
synchronized (AppController.class) {
appController = mInstance;
}
return appController;
}
public RequestQueue getRequestQueue() {
if (this.mRequestQueue == null) {
this.mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return this.mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (this.mImageLoader == null) {
this.mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
if (TextUtils.isEmpty(tag)) {
tag = TAG;
}
req.setTag(tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (this.mRequestQueue != null) {
this.mRequestQueue.cancelAll(tag);
}
}
}
8.Create LruBitmapCache class: By using volley library downloading and caching of image is very simple. The code of this class is given below.
package com.techiesatish.youtubeintegration;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.toolbox.ImageLoader;
public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {
public static int getDefaultLruCacheSize() {
return ((int) (Runtime.getRuntime().maxMemory() / 1024)) / 8;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
protected int sizeOf(String key, Bitmap value) {
return (value.getRowBytes() * value.getHeight()) / 1024;
}
public Bitmap getBitmap(String url) {
return (Bitmap) get(url);
}
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
9. Create a VideoDetails class: In this class we are using setter and getter method to update and retrieve the values of videos.
package com.techiesatish.youtubeintegration;
public class VideoDetails {
String VideoName;
String VideoDesc;
String URL;
String VideoId;
public void setVideoName(String VideoName){
this.VideoName=VideoName;
}
public String getVideoName(){
return VideoName;
}
public void setVideoDesc(String VideoDesc){
this.VideoDesc=VideoDesc;
}
public String getVideoDesc(){
return VideoDesc;
}
public void setURL(String URL){
this.URL=URL;
}
public String getURL(){
return URL;
}
public void setVideoId(String VideoId){
this.VideoId=VideoId;
}
public String getVideoId(){
return VideoId;
}
}
10. Create a VideoActivity: We will create an Activity to show Youtube Video, We are using YoutubePlayerView to show videos. This is our XML file of activity.
<LinearLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android" rel="nofollow">http://schemas.android.com/apk/res/android</a>"
xmlns:app="<a href="http://schemas.android.com/apk/res-auto" rel="nofollow">http://schemas.android.com/apk/res-auto</a>"
xmlns:tools="<a href="http://schemas.android.com/tools" rel="nofollow">http://schemas.android.com/tools</a>"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.techiesatish.youtubeintegration.VideoActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/youtubeview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
10.2 VideoActivity.java: This Activity extends YouTubeBaseActivity. In this Activity we are getting video id from ChannelActivity and using curVideo()
method to show the video.
package com.techiesatish.youtubeintegration;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Config;
import android.util.Log;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class VideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView youTubePlayerView;
String API_KEY="Your API Key";
private static final int RECOVERY_REQUEST = 1;
String TAG="VideoActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
youTubePlayerView=(YouTubePlayerView)findViewById(R.id.youtubeview);
youTubePlayerView.initialize(API_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Bundle bundle = getIntent().getExtras();
String showVideo = bundle.getString("videoId");
Log.e(TAG,"Video" +showVideo);
youTubePlayer.cueVideo(showVideo);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
Toast.makeText(this, "Error Intializing Youtube Player", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
getYouTubePlayerProvider().initialize(API_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubePlayerView;
}
}
11. Now add internet permission and define AppController
in Manifest File.
<manifest xmlns:android="<a href="http://schemas.android.com/apk/res/android" rel="nofollow">http://schemas.android.com/apk/res/android</a>"
package="com.techiesatish.youtubeintegration">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".ChannelActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".VideoActivity">
</activity>
</application>
</manifest>
Now run this App and enjoy!!! If you are facing any problems let me know in a comment box. I will happy to help you. You can download this code from Github. You can also check other helpful tutorials.
Reference: Official Youtube Developer docs
Demo:Demo on Youtube