Home Mobile Android Studio Integrate YouTube Data APIs on Android

Integrate YouTube Data APIs on Android

0
548

A complete and exhaustive tutorial that shows how to integrate and use YouTube APIs to develop a mobile app for Android.

In recent years, YouTube has established itself as the most well-known and used platform for sharing and viewing videos both on mobile and desktop. In particular, in recent years, the ever increasing popularity of the content offered has meant that it was essential to integrate the data and information offered by YouTube in their web app and applications.

To make this task simple for developers, Google has built (and improved over the years) APIs for the use and management of audiovisual content offered by YouTube and that are named YouTube Data API v3. In particular, the features offered by the API are many, such as the ability to view videos and get their thumbnail.

In this article we will analyze in detail the steps to be taken to integrate YouTube Data API starting from a new Android project to display a video and a list of thumbnails. In particular, when the user clicks on the thumbnail the current video will be replaced by the selected one.

Enabling YouTube Data API v3

Like all APIs provided by Google, YouTube Data API v3 must also be enabled through the Google API Console to be integrated into the Android application. To obtain the key, the following steps must be taken:

  • get the SHA-1 hash key for debugging;
  • create a new project on the Google Developer Console;
  • enable the YouTube Data API v3;
  • restrict the use of the key only to Android apps and to the SHA-1 hash key provided.

Proceeding in order, we open a window of our terminal and move inside the folder bin of the jdk installed on our machine and execute the command:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

when the password is requested to generate the hash keys, just type the word android and click enter. It keytool will generate an output similar to the one shown in the figure.

Finally, we copy the SHA-1 hash key as we will use it later in this guide.

Let’s connect now to the Google API Console and access the platform with our account. From the main menu click on the item Select a project or on the name of the current project to open the following modal.

Click on New Project located at the top right and in the screen that appears we type as the name of the project YouTubeDataApiTutorial . Then click on Create .

Once the creation is complete, select the newly created project to display the dashboard.

We click on the Library item in the side menu and look for the YouTube Data API v3 service .

We click on the result obtained to be sent back to the detail page of the library. In this detailed sheet you can find the essential information of the library (description, last update date, etc.) and you can enable and test the provided APIs.

We enable the library by clicking on the enable button and wait for the API dashboard to load.

Like all services and APIs offered by Google, it is necessary to create login credentials for operation. To do so, click on the Create Credentials button temporarily present in the Overview screen, or click on the Credentials section in the side menu. We fill in the form submitted by selecting:

  • the YouTube Data API v3 as a choice for the used APIs;
  • Android as a device from which calls will be made in order to limit them;
  • Public data as the type of data that you want to access through the application.

By clicking on Which credentials do I need? the desired credentials will be generated according to the choices made previously.

Finally, to prevent third parties from misusing our credentials and avoiding quota theft, we restrict access to newly created credentials. From the project dashboard, click on the Credentials item in the side menu and select the key created previously. In the screen that appears we can see information about:

  • the date of creation;
  • the creator of the key;
  • the API key;
  • the name of the key;
  • the restrictions section.

In this last section, we select the Android App entry and associate the key with the as shown in the following figure.

Finally, click on save to make the changes effective.

Library download

The easiest way to integrate YouTube Data API v3 into an Android project is to pass the library download at the following link.

Open the Download section by clicking on the homonymous item from the side menu and download the YouTubeAndroidPlayerApi-1.2.2.zip archive .

Unpack the archive and explore the generated folder that consists of the following subfolders

FolderDescription
docsfolder containing the YouTubeAndroidPlayerApi.jar library
libsfolder containing the YouTubeAndroidPlayerApi.jar library
samplean example of an Android application

Now we are finally ready to work on the Android project.

Creation and set-up of the project

We create a new Android project with Android Studio as shown in this lesson , setting the following parameters

ParameterValue
Application NameYouTubeDataApiTutorial
API target for Phone and TabletAPI 19: Android 4.4 (KitKat)
Activity TemplateEmpty Activity
Activity NameMainActivity

At the end of the wizard, click on Finish and we wait for the completion of the project and the automatic opening of the project.

In the Project section , we select the Project Files view that allows us to have a full view of all the folders in our project, including the libs folder in which we are going to import the YouTubeAndroidPlayerApi.jar library previously downloaded.

We now open the build.gradle of the app module and add the following dependencies.

dependencies {
    // . . .
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation files('libs/YouTubeAndroidPlayerApi.jar')
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    implementation 'com.jakewharton:butterknife:8.8.1'
    // . . .
}

Finally, we click on Sync Now (alternatively Tools> Android> “Sync Project with Gradle Files” ), to make the changes effective.

In this way we have:

  • integrated cardview support;
  • added the butterknife library which has already been discussed earlier in this lesson;
  • integrated YouTube video management library.

Now let’s add a new Value resource file inside the values folder of res and let’s call ityotube_api_key.xml. Open it and add in it the API key previously obtained as follows:

    YOUR_API_KEY

In this way the Key API will be easily loadable inside the Activity through the method getString of Activity. Furthermore, having separated the key from the string.xml file allows us to easily exclude it from the project by adding the path to the .gitignore file .

View a video through YouTubePlayerView

The display of a video via the player offered by YouTubeAndroidPlayerAPI it consists of three steps:

change the layout to add the widget YouTubePlayerView;
extension of the class YouTubeBaseActivity;
interface implementation YouTubePlayer.OnInitializedListener.

Open the layout activity_main.xml and replace the ConstraintLayout default with the following RelativeLayout containing within it the widget YouTubePlayerViewoffered by the YouTube library.

Let’s move into the class now MainActivity and at the same time extend the class YouTubeBaseActivity and implement the interface YouTubePlayer.OnInitializedListener as follows:

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
    // . . .
    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer,
                                        boolean wasRestored) {
        // . . .
    }
    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        // . . .
    }
}

Now let’s define the id of the video we want to display and initialize the widget YouTubePlayerView through the method initialize that requires the YouTube Key API and the Listener.

private final String VIDEO_ID = "2-5Wv9UGkN8";
@BindView(R.id.youtube_player_view)
YouTubePlayerView youTubePlayerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    youTubePlayerView.initialize(getString(R.string.youtube_data_api_key), this);
}

The implementation of the interface requires you to specify the dell ‘behavior Activitywhen the player initialization succeeds, onInitializationSuccessand when it fails, onInitializationFailure. If successful, we will verify that the player has actually been initialized and if the player is restored from a previously saved state. If the value of the boolean wasRestoreis true, then the video will resume from where the user has stopped, otherwise it will be reloaded from the beginning through the method cueVideo. In particular, the method cueVideohas the task of loading the thumbnail and preparing the player to perform the service without downloading any data until the user clicks the play.

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer,
                                    boolean wasRestored) {
    if(null== youTubePlayer) return;
    if (!wasRestored) {
        youTubePlayer.cueVideo(VIDEO_ID);
    }
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
    Toast.makeText(this, "Failed to initialize YouTube Video Player.", Toast.LENGTH_LONG).show();
}

Now run the application on our Android device or on the emulator and we will get the following result.

As we have noted, this solution is easy and immediate, but at the same time forces us to extend the class YouTubeBaseActivity, which in turn extends Activity, instead of the AppCompatActivity fundamental, to support the features of the actionBar and for creating view more complex. In the following section we will see a more efficient and less restrictive solution.

The complete code of this solution can be found on github at the following link.

View a video using YouTubePlayerSupportFragment

An alternative solution to integrate the YouTube player into your app is the use of the class YouTubePlayerSupportFragment. This class defines one fragment containing a type object YouTubePlayerView that allows video viewing. This approach does not require extending any Activity supplied by the library, as in the case of direct use of the YouTubePlayerView , where ours MainActivity extended the class YouTubeBaseActivity.

The steps to take are slightly different than those seen previously. In particular, the operations to be performed are as follows:

  • layout modification to add a type fragment YouTubePlayerSupportFragment;
  • interface implementation YouTubePlayer.OnInitializedListener;
  • initialization of the YouTube player.

Let’s start by modifying the activity_main.xml layout to add a new fragment type YouTubePlayerSupportFragment as follows.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
        android:id="@+id/youtube_fragment"
        android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

We open the one MainActivityto which this screen is connected and implement the interface YouTubePlayer.OnInitializedListener.

public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
// . . .
@Override
protected void onStart() {
super.onStart();
mYuoTubePlayerFrag.initialize(getString(R.string.youtube_data_api_key), this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer,
boolean wasRestored) {
// . . .
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
// . . .
}
// . . .
}

At this point, we initialize a list of YouTube video ids and initialize the YouTubePlayerSupportFragment following.

private final List<String> videos =
Arrays.asList("20bpjtCbCz0", "bI31WqFDxNs", "D86RtevtfrA", "xZNBFcwd7zc", "2-5Wv9UGkN8", "Z5ezsReZcxU");
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerSupportFragment mYuoTubePlayerFrag;
private YouTubePlayer mYouTubePlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mYuoTubePlayerFrag =
(YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_fragment);
}
@Override
protected void onStart() {
super.onStart();
mYuoTubePlayerFrag.initialize(getString(R.string.youtube_data_api_key), this);
}

Similarly to what is seen with the YouTubePlayerView, to initialize the it YouTubePlayerSupportFragment is necessary to call the initialize method passing in input the YouTube key and the Listener.

We implement, now, the methods of Listener defining the behavior of our application in case the initialization of the object YouTubePlayer has happened successfully or not.

If successful, we will check if the player is restored from a previously saved state. If not, we will set the video to display via the function cueVideo.

In the event of a failure, we will verify if the error can be restored by the user. If it should be resettable, then a dialog box will be shown to resolve this initialization error. The dialog box will show a localized error message and, once confirmed by the user (by touching the dialog box), will direct the dialog to the Play Store, if the YouTube app is not updated or missing, or to the settings of system, if the YouTube app is disabled on the device. This is possible thanks to the method getErrorDialogthat accepts as input parameters the one Activity in which to create the dialog and the requestCode used to invoke the method startActivityForResult.

If the error is not resolvable by the user, an error message will be shown Toast.

The implementation for completeness is shown below.

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer,
boolean wasRestored) {
if (!wasRestored) {
mYouTubePlayer = youTubePlayer;
mYouTubePlayer.cueVideo(videos.get(0));
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), youTubeInitializationResult.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}

Before running the application, we disable the YouTube application to see the behavior of the method getErrorDialogand launch the application, obtaining the result in the figure.

Now that we have implemented the player display, we add the list of thumbnails.

Creating a clickable thumbnail list

The library YouTubeAndroidPlayerAPI offers the ability to view the thumbnail of a YouTube video or playlist through the class YouTubeThumbnailView. The process to perform this operation is quite simple and consists of the following steps:

  • creating a new layout to show a CarView content type widget YouTubeThumbnailView;
  • modification of the main layout for the integration of one RecyclerView in which to display the thumbnails;
  • creation of a Adapter and ViewHolder for the RecyclerView;
  • modification of MainActivity the initialization of the RecyclerView.

In this section we will focus mostly on the creation of ‘ Adapter in order to display the thumbnails in the RecyclerView. For further details on the RecyclerView reader, refer to the following lesson .

Let’s start by creating a new layout to manage the thumbnail UI. By right-clicking on the layout folder in res , select New -> Layout resource file and enter the name video_item .

Open the file and replace its contents with the following:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/video_cv"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:layout_margin="6dp"
    android:background="@color/white"
    android:clickable="true"
    card_view:cardElevation="5dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardBackgroundColor="@color/white"
    card_view:cardPreventCornerOverlap="true"
    card_view:cardUseCompatPadding="true"
    android:focusable="true">
<com.google.android.youtube.player.YouTubeThumbnailView
        android:id="@+id/youtube_thumbnail"
        android:layout_width="match_parent"
        android:layout_height="130dp"
        android:scaleType="centerCrop"
        android:layout_gravity="center"
        android:visibility="visible"/>
</android.support.v7.widget.CardView>

In this way we have created one CardView that will be high compared to the background of the MainActivity e that contains within it the widget YouTubeThumbnailView, which will take care of displaying the video thumbnail.

Let’s move now inside the activity_main layout and add it inside the RelativeLayout one RecyclerView, which will contain the thumbnails, and one Viewto separate it from the player.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
. . .
<View
        android:id="@+id/separator_view"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/thickness"
        android:layout_margin="@dimen/margin_10dp"
        android:background="@android:color/darker_gray"
        android:layout_below="@+id/youtube_fragment" />
<android.support.v7.widget.RecyclerView
        android:id="@+id/video_rv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/separator_view" />
</RelativeLayout>

Next, we create a new Java class that we will call VideoAdapter to define the Adapter for the RecyclerView. In particular, this operation requires the definition:

  • of the class VideoAdapterViewHolder;
  • the interface ideoAdapterOnClickHandler to capture the event onClick on the thumbnail selected by the user;
  • the definition of the method etVideosData for setting the list of video ids.
  • methods onCreateViewHolder and onBindViewHolder to tie the created element (in this case a thumbnail) to the RecyclerView.

For the implementation of the class VideoAdapterViewHolder, interface VideoAdapterOnClickHandler and method setVideosData, refer to the following link.

Let’s see instead the implementation of the class VideoAdapter.

Having defined the class VideoAdapterViewHolder, it is possible to extend it to the class VideoAdapter. The class constructor will also input both the Listener click event and the YouTube key APIs that will be used by the object YouTubeThumbnailView. The partial implementation is shown below.

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoAdapterViewHolder>{
// . . .
private String mYouTubeApiKey;
public VideoAdapter(VideoAdapterOnClickHandler mClickHandler, String mYouTubeApiKey) {
this.mClickHandler = mClickHandler;
this.mYouTubeApiKey = mYouTubeApiKey;
}
// . . .
}

Next, we implement the method onCreateViewHolder that will return an instance of the class VideoAdapterViewHolder to which the legally defined video_item layout will be associated . The implementation is shown below.

@Override
public VideoAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context parentContex = parent.getContext();
int layoutIdForListItem = R.layout.video_item;
LayoutInflater inflater = LayoutInflater.from(parentContex);
View view = inflater.inflate(layoutIdForListItem, parent, false);
return new VideoAdapter.VideoAdapterViewHolder(view);
}

Finally, all that remains is to implement the method onBindViewHolder. In this method we are going to initialize the object YouTubeThumbnailView through the method initialize that will input the key APIs that have been passed into the class constructor and the Listener. In this case, if Listener is defined dynamically and in this case also requires the implementation of methods onInitializationSuccess e onInitializationFailure. If successful, the following operations will be performed:

  • the video is set up for YouTubeThumbnailLoader which it is responsible for loading the video thumbnails into the YouTubeThumbnailView;
  • set a second listener on the object youTubeThumbnailLoader to check when the upload finishes and release the thumbnail loader.

The implementation of the method is shown below.

@Override
public void onBindViewHolder(VideoAdapterViewHolder holder, int position) {
final int currentPosition = position;
holder.mYouTubeThumbnailView.initialize(mYouTubeApiKey, new YouTubeThumbnailView.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
youTubeThumbnailLoader.setVideo(videoList.get(currentPosition));
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
@Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
youTubeThumbnailLoader.release();
}
@Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
Log.e(TAG, "Youtube Thumbnail Error");
}
});
}
@Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
Log.e(TAG, "Youtube Initialization Failure");
}
});
}

It remains at this point that you update the MainActivity in order to initialize and populate RecyclerView which will contain the thumbnails.

As a first step, we implement the interface VideoAdapterOnClickHandler defined within the class Adapter as follows.

public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener,
VideoAdapter.VideoAdapterOnClickHandler {
// . . .
@Override
public void onClick(String selectedTrailer) {
if (mYuoTubePlayerFrag != null &amp;&amp; mYouTubePlayer != null) {
mYouTubePlayer.cueVideo(selectedTrailer);
}
}
}

In particular, in the body of the method we onClick verify if the mYuoTubePlayerFrag and the mYouTubePlayer have been initialized and in this case we set the video selected by the user as a new video that will be displayed in the player.

Within the method onCreate:

  • we create a new one LinearLayoutManager o display the contents of the RecyclerView vertical and set it as new LayoutManager for the RecyclerView;
  • we create a new one by VideoAdapter passing the listener and the YouTube API key as values;
  • we set the list of video ids for the Adapter.
@BindView(R.id.video_rv)
RecyclerView mVideoRecyclerView;
private VideoAdapter mVideoAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
//. . .
LinearLayoutManager trailerLayoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mVideoRecyclerView.setLayoutManager(trailerLayoutManager);
mVideoRecyclerView.setHasFixedSize(true);
mVideoAdapter = new VideoAdapter(this, getString(R.string.youtube_data_api_key));
mVideoAdapter.setVideosData(videos);
}

Finally, let’s set the mVideoAdapternew one Adapterfor the RecyclerView.

@Override
protected void onStart() {
// . . .
mVideoRecyclerView.setAdapter(mVideoAdapter);
}

Running the application we will get the following result.

The code for this article can be found on GitHub.

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here