Search code examples
androidyoutubeyoutube-apiandroid-youtube-api

Get Video Title inside onLoaded() method


I know that I can get Video Id inside onLoaded() method of YoutubePlayer StateChangeListener, like this:

    @Override
    public void onLoaded(String s) {

        // 's' contains Video ID
    }

But now just for an experiment, I want to know How could I get Video Title...

Updated

    @Override
    public void onLoaded(String s) {

        // 's' contains Video ID

        Toast.makeText(YouTubeViewActivity.this, s, Toast.LENGTH_SHORT).show();

        String youtubeUrl = "https://www.youtube.com/watch?v=" + s;
        Toast.makeText(YouTubeViewActivity.this, youtubeUrl, Toast.LENGTH_SHORT).show();

        try {
            if (youtubeUrl != null) {
                Toast.makeText(YouTubeViewActivity.this, "Found URL", Toast.LENGTH_SHORT).show();

                URL embededURL = new URL("http://www.youtube.com/oembed?url=" + youtubeUrl + "&format=json");

                strTitle = new JSONObject(IOUtils.toString(embededURL)).getString("title");
                Toast.makeText(YouTubeViewActivity.this, strTitle, Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Solution

  • Here how its done

    String video_title;
    
    @Override
    public void onLoaded(String s) {
    
        String youtubeUrl = "https://www.youtube.com/watch?v=" + s;
    
        try {
            if (youtubeUrl != null) {
                URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
                    youtubeUrl + "&format=json");
    
                video_title = new JSONObject(IOUtils.toString(embededURL)).getString("title");
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }