1
votes

I've the layout for a YouTube video. I would like to set the video's Thumbnail and Title. (I succeeded to set the thumbnail but not the title)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1.0">

    <com.google.android.youtube.player.YouTubeThumbnailView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="6dp"
        android:layout_marginTop="10dp"
        android:id="@+id/youtubeThumbnailView"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="YouTube Video"
        android:textSize="20sp"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:id="@+id/textViewTitle"/>
</LinearLayout>

I set the Thumbnail here:

YouTubeThumbnailView youTubeThumbnailView = (YouTubeThumbnailView) newChild.findViewById(R.id.youtubeThumbnailView);
youTubeThumbnailView.initialize(YouTubePlayer.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
    @Override
    public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {   
        youTubeThumbnailLoader.setVideo("FM7MFYoylVs");
        youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
             @Override
             public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
                  youTubeThumbnailLoader.release();
             }

             @Override
             public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
             }
        });
    }

    @Override
    public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
    }
});

How do I get the title from the video?

I saw a solution here: Get title of YouTube video

but I'm not sure if this is the correct way. I guess that YouTube API lets us get the title in an easier way such as: youTubeThumbnailView.getText() for example.

4

4 Answers

3
votes
private void getVideoInfo(){

    // volley
    StringRequest stringRequest = new StringRequest(
            Request.Method.GET,
            "https://www.googleapis.com/youtube/v3/videos?id=" + keyYouTubeVideo + "&key=" +
                    API_KEY +
                    "&part=snippet,contentDetails,statistics,status",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("items");

                        JSONObject object = jsonArray.getJSONObject(0);
                        JSONObject snippet = object.getJSONObject("snippet");

                        String title = snippet.getString("title");


                        Log.d("stuff: ", "" + title);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.activity_main, error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }){};

    // Request (if not using Singleton [RequestHandler]
    // RequestQueue requestQueue = Volley.newRequestQueue(this);
    // requestQueue.add(stringRequest);

    // Request with RequestHandler (Singleton: if created)
    RequestHandler.getInstance(MainActivity.activity_main).addToRequestQueue(stringRequest);


}
2
votes

you can get it by using google api as : https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=YOUR_VIDEO_ID&key=KEY

1
votes

Json data from youtube is:

{...
 "items": [
  {
   "kind": "youtube#video",
   "etag": ".....",
   "id": "....",
   "snippet": {
    "publishedAt": ".....",
    "channelId": "...",
    "title": "This is the title",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://....jpg",
      "width": 120,
      "height": 90
....

To get the title:

JsonArray items = jsondata.getAsJsonArray("items");
JsonObject snippet = item.getAsJsonObject("snippet");
String title = snippet.get("title").getAsString();

I recommend use https://github.com/koush/ion to load data.

0
votes

I like to achieve this using https://www.youtube.com/get_video_info. The response is quick will give you a lot of extra useful information as well. It is in query string format and has a parameter "player_response" which is a JSON object containing every piece of information you might need about the video.

private static final Pattern YOUTUBE_ID_PATTERN = Pattern.compile("(?<=v\\=|youtu\\.be\\/)\\w+");
private static final Gson GSON = new GsonBuilder().create();

public static String getYouTubeTitle(String url) {
    Matcher m = YOUTUBE_ID_PATTERN.matcher(url);
    if (!m.find())
        throw new IllegalArgumentException("Invalid YouTube URL.");
    JsonElement element = getYoutubeInfo(m.group());
    // The "videoDetails" object contains the video title
    return element.getAsJsonObject().get("videoDetails").getAsJsonObject().get("title").getAsJsonPrimitive().getAsString();
}

public static JsonElement getYoutubeInfo(String youtubeID) throws MalformedURLException, IOException {
    String url = "https://www.youtube.com/get_video_info?video_id=" + youtubeID;
    HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
    connection.addRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36");
    connection.connect();

    String content = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8); // Apache commons. Use whatever you like 
    connection.disconnect();

    String[] queryParams = content.split("\\&"); // It's query string format, so split on ampterstands
    for (String param : queryParams) {
        param = URLDecoder.decode(param, StandardCharsets.UTF_8.name()); // It's encoded, so decode it
        String[] parts = param.split("\\=", 2); // Again, query string format. Split on the first equals character
        if (parts[0].equalsIgnoreCase("player_response")) // We want the player_response parameter. This has all the info
            return GSON.fromJson(parts[1], JsonElement.class); // It's in JSON format, so you use a JSON deserializer to deserialize it
    }

    throw new RuntimeException("Failed to get info for video: " + youtubeID);
}