Search code examples
androidandroid-youtube-api

Android: Get youtubeVideo Id from URL for YouTubePlayer


Tried below code but it will not handle all the cases like

1.)"https://youtu.be/zuf8A0udHrs"

2.)"https://www.youtube.com/watch?v=zuf8A0udHrs"

private boolean isValidUrl(String url) {

    if (url == null) {
        return false;
    }
    if (URLUtil.isValidUrl(url)) {
        // Check host of url if youtube exists
        Uri uri = Uri.parse(url);
        if ("www.youtube.com".equals(uri.getHost())) {
            return true;
        }
        // Other way You can check into url also like 
        //if (url.startsWith("https://www.youtube.com/")) {
            //return true;
        //}
    }
    // In other any case
    return false;
}

Solution

  • I think you can use regex to check a valid link.

    String pattern = "http(?:s?):\\/\\/(?:www\\.)?youtu(?:be\\.com\\/watch\\?v=|\\.be\\/)([\\w\\-\\_]*)(&(amp;)?‌​[\\w\\?‌​=]*)?";
            String link1 = "https://youtu.be/zuf8A0udHrs";
            String link2 = "https://www.youtube.com/watch?v=zuf8A0udHrs";
    
            if(link2.matches(pattern)) {
                System.out.println("YES");
            } else {
                System.out.println("NO");
            }