Search code examples
javaandroidyoutube

How get the thumbnail from YouTube


Thumbnail from the video in YouTube.

I want to add the ability to add images from video which I get in my method useLinkInput.

Now I have a dialog, where I have the following code:

public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    Toast.makeText(getContext(), "ОК", Toast.LENGTH_SHORT).show();
    String string = input.getText().toString();
    useLinkInput(string);
}

And method useLinkInput:

private void useLinkInput(String input) {
    Uri uri = Uri.parse(input);
    String videoID = uri.getQueryParameter("v");
    url = "http://img.youtube.com/vi/" + videoID +"/0.jpg";
    Log.d("url", url);
}

When the user pastes the link in the dialog and presses OK, I get this in the log image:

D/url: http://img.youtube.com/vi/null/0.jpg

But it is null* (it didn’t show the image).


Solution

  • For example, your YouTube video URL is as below.

    String youtubeUrl = "https://www.youtube.com/watch?v=Rxo0Upfz48Q";
    

    In this URL parameter, v=Rxo0Upfz48Q stands for the video ID. So, in the above URL videoID is Rxo0Upfz48Q.

    You can get videoID using the below code.

    Uri uri = Uri.parse(youtubeUrl);
    String videoID = uri.getQueryParameter("v");
    

    Now using videoID you can make the URL to get the first frame of that YouTube video like below.

    String url = "http://img.youtube.com/vi/" + videoID + "/0.jpg";
    

    Now you can get a thumbnail image from the above URL and display in your imageview.