Fetches video ID from given youtube video URL. - Android App

Android examples for App:Popular App

Description

Fetches video ID from given youtube video URL.

Demo Code


//package com.java2s;

import android.text.TextUtils;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    /**/*from  ww w  .  ja  va2  s .  c  o  m*/
     * Fetches video ID from given you tube video URL.
     *
     * @param videoUrl
     * @return video ID
     */
    public static String getVideoId(String videoUrl) {
        String videoId = null;

        // Sample YouTube URLs.
        // "http://www.youtube.com/watch?v=8mKTiD02v3M";
        // "http://www.youtube.com/v/8mKTiD02v3M?version=3&autohide=1";
        // "http://youtu.be/8mKTiD02v3M";

        URL url;
        try {

            url = new URL(videoUrl);

            if (!TextUtils.isEmpty(videoUrl)) {
                if (videoUrl.contains("?v=")) {
                    videoId = videoUrl.split("\\?v=")[1];
                } else if (videoUrl.contains("?version")) {
                    videoId = url.getPath().split("\\/")[2];
                } else {
                    videoId = url.getPath().split("\\/")[1];
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return videoId;
    }
}

Related Tutorials