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>
Related
I have set up a YouTubePlayerView which works perfectly but I face a weird problem. When I go to another Fragment and then go back, YouTubePlayerView can't load the video, even if the exact code is executed.
private String currentVideoID "p450mjB3mxc";
private YouTubePlayerView youtubeView;
private void init(View view)
{
youtubeView = view.findViewById(R.id.youtubeView);
new YoutubeHelper(youtubeView,currentVideoID,this);
}
public void setYoutubePlayer(YouTubePlayer youtubePlayerPublic)
{
this.youtubePlayer = youtubePlayerPublic;
youtubePlayer.loadVideo(currentVideoID);
}
YoutubeHelper.class:
public class YoutubeHelper {
public final static String YoutubeAPIKey="MY_API_KEY";
public YouTubePlayer youtubePlayerPublic;
private YouTubePlayerView youTubeView;
public YoutubeHelper(YouTubePlayerView youTubeView, String initialVideo, MainFragment fragment)
{
this.youTubeView = youTubeView;
init(initialVideo,fragment);
}
private void init(String initialVideo,final MainFragment fragment)
{
youTubeView.initialize(YoutubeAPIKey,
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
final YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo(initialVideo);
youtubePlayerPublic = youTubePlayer;
fragment.setYoutubePlayer(youTubePlayer);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
Log.d("Youtube Error:", youTubeInitializationResult.toString());
}
});
}
}
I have tried this answer with no success at all.
Any ideas?
I found the solution if anyone facing the same problem. Before leaving the fragment do:
youtubePlayer.pause();
youtubePlayer.release();
I am creating a listview in Android. When I click on the item in the listview, it goes to second activity with the Youtubeplayer. But instead of playing the video, a message appears inside the Youtube player saying
An error occurred while initializing the youtube player
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final String[] sublectures = {"Part 1", "Part 2"};
ListAdapter appadapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sublectures);
ListView list2 = findViewById(R.id.list2);
list2.setAdapter(appadapter1);
list2.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String lecture = String.valueOf(parent.getItemAtPosition(position));
Intent startintent = new Intent(getApplicationContext(),Main3Activity.class);
startActivity(startintent);
}
});
}}
This is Main3Activity
public class Main3Activity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "AIzaSyBdVOqvu3C-MTnmO0iNOgeKBCSmb9ULrXc";
public static final String VIDEO_ID = "W2TYS_Jvzjc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtubePlayerView);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure (YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult){
Toast.makeText(this, "Fail to Load", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
player.cueVideo(VIDEO_ID);
}
}
}
Try out this code works for me
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.YouTubePlayerView;
public class VideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView youTubePlayerView;
String API_KEY="AIzaSyB2TtG6UjEtDWfzxHvQCf2DJxkUPfJI1Lc";
private static final int RECOVERY_REQUEST = 1;
String TAG="VideoActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
youTubePlayerView=(YouTubePlayerView)findViewById(R.id.youtube);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Bundle bundle = getIntent().getExtras();
String showVideo = bundle.getString("videoId");
youTubePlayer.cueVideo(showVideo);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
Toast.makeText(this, "Error Intializing Youtube Player", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
getYouTubePlayerProvider().initialize(API_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubePlayerView;
}
}
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());
}
}
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.
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"/>