Thursday, October 12, 2017

Build android app with youtube playlist

Build android app with youtube playlist

Below code snippets will explain how to integrate Youtube Playlist in our Android Application to make a Youtube Player. This app will retrieve playlist from youtube API and show it in list. Onclick of the videos will play the videos.




Get youtube playlist from youtube API by passing playlist string in a thread.

private void searchOnYoutube(final String playList){
  new Thread(){
   public void run(){
    YoutubeConnector yc = new YoutubeConnector(SearchActivity.this);
    //searchResults = yc.search(keywords);
    searchResults = yc.playList(playList);
    handler.post(new Runnable(){
     public void run(){
      updateVideosFound();
     }
    });
   }
  }.start();
 }


Get list of thumbnail image, title and description of the playlist

private void updateVideosFound(){
  ArrayAdapter<VideoItem> adapter = new ArrayAdapter<VideoItem>(getApplicationContext(), R.layout.video_item, searchResults){
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null){
     convertView = getLayoutInflater().inflate(R.layout.video_item, parent, false);
    }
    ImageView thumbnail = (ImageView)convertView.findViewById(R.id.video_thumbnail);
    TextView title = (TextView)convertView.findViewById(R.id.video_title);
    TextView description = (TextView)convertView.findViewById(R.id.video_description);
    
    VideoItem searchResult = searchResults.get(position);
    
    Picasso.with(getApplicationContext()).load(searchResult.getThumbnailURL()).into(thumbnail);
    title.setText(searchResult.getTitle());
    description.setText(searchResult.getDescription());
    return convertView;
   }
  };   
  
  videosFound.setAdapter(adapter);
 }

Connect to youtube API and get details

public YoutubeConnector(Context context) {
  youtube = new YouTube.Builder(new NetHttpTransport(),
    new JacksonFactory(), new HttpRequestInitializer() {
   @Override
   public void initialize(HttpRequest hr) throws IOException {}
  }).setApplicationName(context.getString(R.string.app_name)).build();

  try{
   query = youtube.search().list("id,snippet");
   query.setKey(KEY);
   query.setType("playlist");
   query.setFields("items(id/playlistId,snippet/title,snippet/description,snippet/thumbnails/default/url)");


   playListItemList = youtube.playlistItems().list("id,contentDetails,snippet,status");
   playListItemList.setKey(KEY);
   playListItemList.setFields("items(id,status/privacyStatus,snippet/description,snippet(title,thumbnails/default/url),contentDetails)");
   playListItemList.setMaxResults((long) 50);


  }catch(IOException e){
   Log.d("YC", "Could not initialize: "+e);
  }
 }

Store playlist items in list

public List<VideoItem> search(String keywords){
  query.setQ(keywords);
  try{
   SearchListResponse response = query.execute();
   List<SearchResult> results = response.getItems();

   List<VideoItem> items = new ArrayList<VideoItem>();
   for(SearchResult result:results){
    VideoItem item = new VideoItem();
    item.setTitle(result.getSnippet().getTitle());
    item.setDescription(result.getSnippet().getDescription());
    item.setThumbnailURL(result.getSnippet().getThumbnails().getDefault().getUrl());
    item.setId(result.getId().getVideoId());
    items.add(item);
   }
   return items;
  }catch(IOException e){
   Log.d("YC", "Could not search: "+e);
   return null;
  }
 }

 public List<VideoItem> playList(String playList) {

  //final String[] playlistIds = params[0];


  try {

   playListItemList.setPlaylistId(playList);

   PlaylistItemListResponse playlistItemListResponse = null;
   playlistItemListResponse = playListItemList.execute();


   List<VideoItem> items = new ArrayList<VideoItem>();

   for (int i=0;i<playlistItemListResponse.getItems().size();i++){

    VideoItem item = new VideoItem();
    item.setTitle(playlistItemListResponse.getItems().get(i).getSnippet().getTitle());
    item.setDescription(playlistItemListResponse.getItems().get(i).getSnippet().getDescription());
    item.setThumbnailURL(playlistItemListResponse.getItems().get(i).getSnippet().getThumbnails().getDefault().getUrl().replace("default","hqdefault"));
    //item.setThumbnailURL(playlistItemListResponse.getItems().get(i).getSnippet().getThumbnails().getDefault().getUrl());
    item.setId(playlistItemListResponse.getItems().get(i).getContentDetails().getVideoId());
    items.add(item);
   }
   return items;
  } catch (IOException e) {
   e.printStackTrace();
   return null;
  }
 }
 


Add onclicklistner and onclick of video from playlist play the video

private void addClickListener(){
  videosFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> av, View v, int pos,
     long id) {    
    Intent intent = new Intent(getApplicationContext(), PlayerActivity.class);
    intent.putExtra("VIDEO_ID", searchResults.get(pos).getId());
    startActivity(intent);
   }
   
  });
 }

public class PlayerActivity extends YouTubeBaseActivity implements OnInitializedListener {
 
 private YouTubePlayerView playerView;
 
 @Override
 protected void onCreate(Bundle bundle) {
  super.onCreate(bundle);
  
  setContentView(R.layout.activity_player);

     playerView = (YouTubePlayerView)findViewById(R.id.player_view);
     playerView.initialize(YoutubeConnector.KEY, this);         
 }

 @Override
 public void onInitializationFailure(Provider provider,
   YouTubeInitializationResult result) {
  Toast.makeText(this, getString(R.string.failed), Toast.LENGTH_LONG).show();
 }

 @Override
 public void onInitializationSuccess(Provider provider, YouTubePlayer player,
   boolean restored) {
  if(!restored){   
   player.cueVideo(getIntent().getStringExtra("VIDEO_ID"));
  }
 }
}

activity_player.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <com.google.android.youtube.player.YouTubePlayerView        
        android:id="@+id/player_view" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    

Share:

0 comments:

Post a Comment

Popular Posts

Contact Form

Name

Email *

Message *