How to autoplay video through YouTube Player - android

I am developing an app in which I have shown YouTube videos thumbnails in RecyclerView and there is YouTube Player fragment on top which plays the user selected video. I succeed in doing so. but the problem is that I want to auto play the user selected video.
below is my code:
main_activity.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2"
android:orientation="vertical"
tools:context="com.example.pc.fkidshell.Main2Activity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/VideoFragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_below="#+id/my_thirdtoolbar"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/VideoList"
android:layout_below="#+id/VideoFragment"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
secvideo_row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/thumbnailView"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
Main_Activity.java:
public class Main2Activity extends AppCompatActivity implements YouTubeThumbnailView.OnInitializedListener, YouTubeThumbnailLoader.OnThumbnailLoadedListener, YouTubePlayer.OnInitializedListener {
YouTubePlayerFragment playerFragment;
YouTubePlayer Player;
YouTubeThumbnailView thumbnailView;
YouTubeThumbnailLoader thumbnailLoader;
RecyclerView VideoList;
RecyclerView.Adapter adapter;
List<Drawable> thumbnailViews;
List<String> VideoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
thumbnailViews = new ArrayList<>();
VideoList = (RecyclerView) findViewById(R.id.VideoList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
VideoList.setLayoutManager(layoutManager);
adapter = new Main2Activity.VideoListAdapter();
VideoList.setAdapter(adapter);
VideoId = new ArrayList<>();
thumbnailView = new YouTubeThumbnailView(this);
thumbnailView.initialize("AIzaSyAXlMCst9tNrTGz4xAZ0mY6mJlkNU-3DAs", this);
playerFragment = (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.VideoFragment);
playerFragment.initialize("AIzaSyAXlMCst9tNrTGz4xAZ0mY6mJlkNU-3DAs", this);
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {
thumbnailLoader = youTubeThumbnailLoader;
youTubeThumbnailLoader.setOnThumbnailLoadedListener(Main2Activity.this);
thumbnailLoader.setPlaylist("PLXRActLQ03oY_6AQb-5EMuKFYQA_fDE40");
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
}
public void add() {
adapter.notifyDataSetChanged();
if (thumbnailLoader.hasNext())
thumbnailLoader.next();
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
thumbnailViews.add(youTubeThumbnailView.getDrawable());
VideoId.add(s);
add();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Player = youTubePlayer;
Player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
VideoList.setVisibility(b ? View.GONE : View.VISIBLE);
}
});
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.MyView> {
public class MyView extends RecyclerView.ViewHolder {
ImageView imageView;
public MyView(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.thumbnailView);
}
}
#Override
public VideoListAdapter.MyView onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.secvideo_row, parent, false);
return new MyView(itemView);
}
#Override
public void onBindViewHolder(VideoListAdapter.MyView holder, final int position) {
holder.imageView.setImageDrawable(thumbnailViews.get(position));
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Player.loadVideo(VideoId.get(position));
//Player.loadVideo(VideoId.get(position));
}
});
}
#Override
public int getItemCount() {
return thumbnailViews.size();
}
}
}

When the Youtube player is initialized, set a player state change listener so that you can play the video when the video is loaded and make sure your activity implements player state callbacks.
Detailed code :
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Player = youTubePlayer;
Player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
VideoList.setVisibility(b ? View.GONE : View.VISIBLE);
}
});
Player.setPlayerStateChangeListener(this); //set player state change listener
}
#Override
public void onAdStarted() {
}
#Override
public void onLoaded(String videoId) {
if(!TextUtils.isEmpty(videoId) && Player != null)
Player.play(); //auto play
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
#Override
public void onError(ErrorReason reason) {
Log.e("onError", "onError : " + reason.name());
}

i hade the same problem, i use YouTubePlayerFragment though and this is what i did.
public async void PlayVideo(params string[] videoId)
{
if (YoutubePlayer != null && videoId != null && videoId.Length > 0)
{
YoutubePlayer.CueVideos(videoId);
await Task.Delay(TimeSpan.FromSeconds(5)); // whait untill the files load.
YoutubePlayer.Play();
}
}
and the player get assigned here
public void OnInitializationSuccess(IYouTubePlayerProvider provider, IYouTubePlayer player, bool wasRestored)
{
if (!wasRestored)
{
YoutubePlayer = player;
PlayVideo(elemnt.VideoSource.ToArray());
}
}

Related

CardView is not showing Youtube Thumbnail view in Android

I have used the Youtube API in my application along with FirebaseRecyclerAdapter and RecyclerView and for some reasons my YouTube Thumbnail is not being shown in my application although I have added it in my CardView and my FirebaseRecyclerAdapter has code to access the CardView but when I start my application and go to that activity no thumbnail is shown over there. I have implemented it as hard coded without Firebase Adapter.
Steps I have tried:
Added layout manager
Adjusting the height and width of cardView and thumbnailView
I am using Android Studio
YouTube class file:
public class YoutubeVideos extends YouTubeBaseActivity {
private RecyclerView YouRecycler;
private DatabaseReference YDatabaseReference;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.youtube_videos);
YDatabaseReference = FirebaseDatabase.getInstance().getReference().child("youtubed");
YouRecycler = (RecyclerView)findViewById(R.id.Youtube_recycler);
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder> YfirebaseRecyclerAdapter = new FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder>(
post2youtube.class,
R.layout.youtube_videos_card,
YoutubeViewHolder.class,
YDatabaseReference
) {
#Override
protected void populateViewHolder(YoutubeViewHolder viewHolder, post2youtube model, int position) {
viewHolder.setYoutube(model.getYoutube());
}
};
YouRecycler.setAdapter(YfirebaseRecyclerAdapter);
}
public static class YoutubeViewHolder extends RecyclerView.ViewHolder {
View yView;
public YoutubeViewHolder(View YitemView) {
super(YitemView);
yView = YitemView;
}
public void setYoutube(final String youtube){
final YouTubePlayerView youPlay = (YouTubePlayerView) yView.findViewById(R.id.youtuber);
youPlay.initialize("Some key",
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(youtube);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
}
}
YouTube RecyclerView file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id ="#+id/Youtube_recycler"/>
</LinearLayout>
YouTube cardView xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_cardView"
android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtuber"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</android.support.v7.widget.CardView>
YoutubePlayer view is too large to be added to a recyclerview.So use a YouTubeThumbnailView instead to display the thumbnails. When the user clicks on one of them, you can start a YouTubePlayerFragment or an activity with a YouTubeplayerView view.
below is the reference code,
in xml :
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginBottom="#dimen/ten_dp"
android:visibility="gone"/>
in java :
// Initializing video player with developer key
youtube_view.initialize(Config.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
youTubeThumbnailLoader.setVideo(videoId);
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
youTubeThumbnailLoader.release();
Toast.makeText(getActivity(), "It's a valid youtube url.", Toast.LENGTH_SHORT).show();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
try {
Toast.makeText(getActivity(), "Not a valid youtube url.", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
}
});

Video is not playing in YoutubePlayer Fragment

I am making an app which uses Youtube player fragment. It is loaded but video is not getting played. Here is my code:
Youtube.java (Fragment)
public class Youtube extends YouTubePlayerFragment {
public Youtube() {
}
public static Youtube newInstance(String url) {
Youtube frag = new Youtube();
Bundle b = new Bundle();
b.putString("url", url);
frag.setArguments(b);
frag.init();
return frag;
}
private void init() {
initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(getArguments().getString("url"));
// player.play();
}
}
});
}
}
Activity:
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
Youtube f = Youtube.newInstance("https://www.youtube.com/watch?v=o49aHgzTOGw");
FragmentManager fragmentManager=getFragmentManager();
fragmentManager.beginTransaction().add(f,"Fragment").commit();
}
Layout:
<FrameLayout>
<fragment class="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/Fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
Where I am going wrong. I am not able to figure it out. Do I need to extend YoutubeBaseActivity? How to achieve this?
I think you should write the code in official way. Take look at here, and download the zip file(sample applications included in the YouTubeAndroidAPIDemo package) here to get the sample. And take look at FragmentDemoActivity.
Basically, you need to do the Activity which include YoutubePlayerFragment as follows:
public class FragmentDemoActivity extends YouTubeFailureRecoveryActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragments_demo);
YouTubePlayerFragment youTubePlayerFragment =
(YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
#Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.youtube_fragment);
}
}
YouTubeFailureRecoveryActivity :
public abstract class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DeveloperKey.DEVELOPER_KEY, this);
}
}
protected abstract YouTubePlayer.Provider getYouTubePlayerProvider();
}
And the fragments_demo.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

Video is playing for a millisecond implemented using youtubeplayer view

I am trying to implement to play youtube video in my app using youtubeplayer view when user clicks on button but its just playing for a millisecond,after that it just stop.App is not crashing but video is also not playing.
Code for the same is-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "xxxx";
String videoId;
String url="http://www.youtube.com/xxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
setContentView(R.layout.activity_video_view);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
videoId=getYoutubeVideoId(url);
Log.e("id",videoId);
//videoId=getIntent().getExtras().getString("url");
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(videoId);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
Log.e("on","buffer");
}
#Override
public void onPaused() {
Log.e("on","pause");
}
#Override
public void onPlaying() {
Log.e("on","play");
}
#Override
public void onSeekTo(int arg0) {
Log.e("on","seekto");
}
#Override
public void onStopped() {
Log.e("on","stop");
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
Log.e("on","ad");
}
#Override
public void onLoaded(String arg0) {
Log.e("on","loaded");
}
#Override
public void onLoading() {
Log.e("on","loading");
}
#Override
public void onVideoEnded() {
Log.e("on","vidEnd");
}
#Override
public void onVideoStarted() {
Log.e("on","vidStart");
}
#Override
public void onError(ErrorReason arg0) {
// TODO Auto-generated method stub
}
};
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
xml file-
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.youtube.player.YouTubePlayerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp" />
warning in logcat-
W/YouTubeAndroidPlayerAPI(8722): YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor com.google.android.youtube.player.YouTubePlayerView{41c88550 V.E..... ........ 0,0-480,270 #7f05003d app:id/youtube_player}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: -8, top: -8, right: -8, bottom: -8 (these should all be positive).
This issue is solved by using youtubeplayer fragment rather than youtubeplayer view.Code for the same is-
xml-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
java file-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String DEVELOPER_KEY = "your api key";
private static final int RECOVERY_DIALOG_REQUEST = 1;
String url="your video url";
String VIDEO_ID;
YouTubePlayerFragment myYouTubePlayerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_view);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
VIDEO_ID=getYoutubeVideoId(url);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
"There was an error initializing the YouTubePlayer (%1$s)",
errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
Add internet permission in your manifest file.

Youtube, loads and plays a list of videos

i'm stuck with implementing following youtube method.
public abstract void loadVideos (List<String> videoIds)
Loads and plays a list of videos.
basically this is part of my code.
My ultimate goal is when user click on listitem that video plays or it automatically plays all three videos.
Can someone please help me.
private static final String1[] arry = {
new String1("Androidify App", "irH3OSOskcE", false),
new String1("Chrome Speed Tests", "nCgQDjiotG0", false),
new String1("Playlist: Google I/O 2012", "PL56D792A831D0C362", true)};
private static final String KEY_CURRENTLY_SELECTED_ID = "currentlySelectedId";
private YouTubePlayerView youTubePlayerView;
private YouTubePlayer player;
private ArrayAdapter<String1> videoAdapter1;
private ListView videoChooser1;
private StringBuilder logString;
private MyPlayerStateChangeListener playerStateChangeListener;
private MyPlaylistEventListener playlistEventListener;
private int currentlySelectedPosition;
private String currentlySelectedId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_controls_demo);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
videoChooser1 = (ListView) findViewById(R.id.listView1);
logString = new StringBuilder();
videoAdapter1 = new ArrayAdapter<String1>(this, android.R.layout.simple_list_item_1, arry);
videoChooser1.setAdapter(videoAdapter1);
videoChooser1.setOnItemClickListener(this);
youTubePlayerView.initialize(DeveloperKey.DEVELOPER_KEY, this);
playlistEventListener = new MyPlaylistEventListener();
playerStateChangeListener = new MyPlayerStateChangeListener();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
this.player = player;
player.setPlaylistEventListener(playlistEventListener);
player.setPlayerStateChangeListener(playerStateChangeListener);
if (!wasRestored) {
playVideoAtSelection();
}
}
#Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubePlayerView;
}
private void playVideoAtSelection() {
String1 selectedEntry = videoAdapter1.getItem(currentlySelectedPosition);
if (selectedEntry.id != currentlySelectedId && player != null) {
currentlySelectedId = selectedEntry.id;
if (selectedEntry.isPlaylist) {
player.loadPlaylist(selectedEntry.id);
} else {
player.loadVideo(selectedEntry.id);
player.loadVideos(List<String>,selectedEntry.id);
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
{
currentlySelectedPosition = pos;
playVideoAtSelection();
}
#Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString(KEY_CURRENTLY_SELECTED_ID, currentlySelectedId);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
currentlySelectedId = state.getString(KEY_CURRENTLY_SELECTED_ID);
}
private void log(String message) {
logString.append(message + "\n");
// eventLog.setText(logString);
}
private final class MyPlaylistEventListener implements PlaylistEventListener {
#Override
public void onNext() {
log("NEXT VIDEO");
}
#Override
public void onPrevious() {
log("PREVIOUS VIDEO");
}
#Override
public void onPlaylistEnded() {
log("PLAYLIST ENDED");
}
}
private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {
String playerState = "UNINITIALIZED";
#Override
public void onLoading() {
playerState = "LOADING";
log(playerState);
}
#Override
public void onLoaded(String videoId) {
playerState = String.format("LOADED %s", videoId);
log(playerState);
}
#Override
public void onAdStarted() {
playerState = "AD_STARTED";
log(playerState);
}
#Override
public void onVideoStarted() {
playerState = "VIDEO_STARTED";
log(playerState);
}
#Override
public void onVideoEnded() {
playerState = "nCgQDjiotG0";
log(playerState);
}
#Override
public void onError(ErrorReason arg0) {
// TODO Auto-generated method stub
}
}
private static final class String1 {
public final String title;
public final String id;
public final boolean isPlaylist;
public String1(String title, String videoId, boolean isPlaylist) {
this.title = title;
this.id = videoId;
this.isPlaylist = isPlaylist;
}
#Override
public String toString() {
return title;
}
}
After few tries i figured it out, it is partially working in case if anyone else needs it
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
this.player = player;
player.setPlaylistEventListener(playlistEventListener);
player.setPlayerStateChangeListener(playerStateChangeListener);
if (!wasRestored) {
ArrayList arrayList = new ArrayList();
arrayList.add((Object)("irH3OSOskcE"));
arrayList.add((Object)("nCgQDjiotG0"));
arrayList.add((Object)("irH3OSOskcE"));
player.loadVideos((List)(arrayList));
//playVideoAtSelection();
}
}

How to use YouTubePlayer api in fragments?

I am using youtube player api in my application,I have used the following code
xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel1"
android:background="#edeae5">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</RelativeLayout>
my Activity:
public class EditBloop extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_bloop);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
}
But here I am using YouTubeBaseActivity,but in my application I want youTubePlayer in a Fragment.
How can I achieve this? I have seen some of the links using YouTubePlayerSupportfragment but I didnt understand them.
Please suggest.
You can do as below
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "key";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;
private static final int RQS_ErrorDialog = 1;
private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;
String log = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
youTubePlayer = player;
Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();
youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {
private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onAdStarted() {
updateLog("onAdStarted()");
}
#Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}
#Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}
#Override
public void onLoading() {
updateLog("onLoading()");
}
#Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}
#Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}
}
private final class MyPlaybackEventListener implements PlaybackEventListener {
private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}
#Override
public void onPaused() {
updateLog("onPaused()");
}
#Override
public void onPlaying() {
updateLog("onPlaying()");
}
#Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}
#Override
public void onStopped() {
updateLog("onStopped()");
}
}
}
The xml
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"/>

Categories

Resources