Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

GAURAV DOBHAL
GAURAV DOBHAL
6,155 Points

Android : Playing YouTube Videos

Hi,

I am trying to create an android app that displays and plays YouTube videos. I am using the YouTube Player APIs for streaming the videos and displaying the videos. The test is working fine. However loading the videos and the thumbnails takes a few seconds and a black screen comes till that time. I have tried using Async Task to load the videos in the background but even that doesen't work perfectly. Writing my Main Activity class below. is there a better way of doing this?

package com.example.blooptroop.youtubeplayer;

import android.app.ListActivity; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast;

import com.example.blooptroop.youtubeplayer.Adapters.VideoListAdapter; import com.example.blooptroop.youtubeplayer.VideoIds.Videolist; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayer.Provider; import com.google.android.youtube.player.YouTubePlayerView; import com.google.android.youtube.player.YouTubeStandalonePlayer;

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {

private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private ListView mListView;
private TextView mText;
private DownloadVideos videos;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    videos=new DownloadVideos();

    youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);

    mText=(TextView)findViewById(R.id.Placeholder);

    mListView=(ListView)findViewById(R.id.listView);

    final Videolist[] videolist=new Videolist[2];
    videolist[0]=new Videolist("DLhdSP4yVVY","Hickory Dickory");
    videolist[1]=new Videolist("GD91r1uzDoA","Old Macdonald");

    VideoListAdapter adapter=new VideoListAdapter(this,videolist);
    mListView.setAdapter(adapter);

    youTubeView.initialize(Config.YOUTUBE_API_KEY, this);

    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent=YouTubeStandalonePlayer.createVideoIntent(MainActivity.this,
                    Config.YOUTUBE_API_KEY, videolist[position].getId());
            startActivity(intent);

        }
    });


}


public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {


        videos.execute(player);

       /* player.cuePlaylist("PLdTYB4ehZlPIBlnCykGp6O51R33hxOKi8");
        youTubeView.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.VISIBLE);
        mText.setVisibility(View.INVISIBLE);*/
}
}


public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
    if (errorReason.isUserRecoverableError()) {
        errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
    } else {
        String error = String.format(getString(R.string.player_error), errorReason.toString());
        Toast.makeText(this, error, Toast.LENGTH_LONG).show();
    }
}

private class DownloadVideos extends AsyncTask<YouTubePlayer,Void,Void>
{

    @Override
    protected Void doInBackground(YouTubePlayer... params) {

                   YouTubePlayer player=params[0];
                   player.cuePlaylist("PLdTYB4ehZlPIBlnCykGp6O51R33hxOKi8");
                   player.play();

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        mText.setVisibility(View.INVISIBLE);
        youTubeView.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.VISIBLE);


    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

1 Answer

Ben Morse
Ben Morse
6,068 Points

Hey man, were you able to solve this? I'm looking into incorporating YouTube videos into my app. Are there any good lesson you recommend checking when tackling this?

GAURAV DOBHAL
GAURAV DOBHAL
6,155 Points

Hey,

Yes I was able to solve mainly using YouTube Fragment Class. This tutorial was very handy http://createdineden.com/blog/post/android-tutorial-how-to-integrate-youtube-videos-into-your-app/