I got an Article object that I want to display in my Activity. An article can have:
-Text(s) : 1 at least or several
-Image(s) : 0 or several
-Video(s) : 0 or several
Each element can be anywhere in the article for example :
-Text / Image / Text / Video
-Video / Image / Video / Text
- etc...
After parsing my article, I add programmatically the content I need: TextView, ImageView, or VideoView(youtube or jwplayer). Actually it works for image and text, but I don't know how I can add several youtube video in a same activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
linearLayout = (LinearLayout) findViewById(R.id.llayout_article);
// Get article to display it
Intent intent = getIntent();
Article article = intent.getParcelableExtra("articleDetails");
//add ImageView & TextView
for (View view : article.getContentSplitInViews(this)) {
this.linearLayout.addView(view);
}
YouTubePlayerSupportFragment frag =
(YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_fragment);
src="g2mmUzNSeDM";
frag.initialize(apiKey, this);
YouTubePlayerSupportFragment frag2 =
(YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_fragment2);
src = "nCgQDjiotG0";
frag2.initialize(apiKey, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.loadVideo(src);
youTubePlayer.play();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
// YouTube error
String errorMessage = youTubeInitializationResult.toString();
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show();
Log.d("errorMessage:", errorMessage);
}
My current xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/scrollViewId"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:id="#+id/llayout_article"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="#+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="#+id/youtube_fragment2"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</ScrollView>
Later I want to add programmaticaly the fragment tag in my XML for each video found in the Article Object.
Actually, there is 2 players in my activity, but only one is playing the video, and action in every players (play/pause/full screen) will do the same thing in the 2 players.
First of all you have to distinguish from two providers by id in onInitializationSuccess().
If the provider is the frag1, call youTubePlayer.loadVideo("g2mmUzNSeDM")
else if the provider is the frag2, call youTubePlayer.loadVideo("nCgQDjiotG0")
(You can add YouTubePlayerView programmatically to your layout if your activity extends YoutubeBaseActivity)
Related
Currently working on application with integrating youtube player in it, all things working fine, the only problem I'm facing is that I'm not able to get onClick call back on youtubePlayerView. I'm trying to toast youtube video title when user click on youtube player. It's working fine when no video is loaded in youtube player but as soon as I initialised the youtubePlayerView and loadVideo clickListener start not working. How to handle clickListener in youtube player?
This is my xml code :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:onClick="onClick"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/player">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubePlayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="onClick"
android:background="#color/black"/>
</RelativeLayout>
<include layout="#layout/video_player_bottom_sheet"/>
</android.support.design.widget.CoordinatorLayout>
My code for playing video :
#Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return mYouTubePlayerView;
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
mYoutubePlayer = youTubePlayer;
mYoutubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
if (!wasRestored) {
mYoutubePlayer.loadVideo("0g0sy2x_vX4");
}
}
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),videoTitle,Toast.LENGTH_SHORT).show();
}
Remove the #Override from your method that you have defined for your method onClick() and add this to your player component in xml
android:clickable="true"
I'm developing an app with Android Studio for which I need the Youtube API. The problem is that I want the video to be played
every time the user clicks on "Reproducir"("play"). So I have researched how to load a video and everybody says to use the function
initializates that will call onInitializationSuccess and playes there. But if I want to load new videos, parsing the url and playing the new videos I can't. I tried calling the initialization everytime the user clicks on Reproducir but in that case It ig.
public class AddVideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
private YouTubePlayerView youTubeView;
private EditText urlTxtView;
private Button playButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_video);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_player_add);
urlTxtView = (EditText) findViewById(R.id.urlYoutube);
playButton = (Button) findViewById(R.id.buttonPlay);
playButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
youTubeView.initialize(Config.YOUTUBE_API_KEY, (YouTubePlayer.OnInitializedListener) view.getContext());
}
});
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
String url = urlTxtView.getText().toString();
Log.d("1",url );
youTubePlayer.loadVideo("a4NT5iBFuZs");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "ERROR:"+result.toString(), Toast.LENGTH_LONG).show();
}
XML Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/action_add_video"
android:textStyle="normal|bold"
android:textSize="30sp"
android:gravity="center_horizontal"
android:layout_marginBottom="20dp" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"/>
<EditText
android:id="#+id/tituloVideo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Titulo"
android:inputType="textPersonName" />
<EditText
android:id="#+id/urlYoutube"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="URL o buscar con #youtube"
android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/buttonCancelar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancelar" />
<Button
android:id="#+id/buttonPlay"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Reproducir" />
<Button
android:id="#+id/buttonGuardar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guardar" />
</LinearLayout>
</LinearLayout>
Log:
W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is obscured by android.view.View{a21cb6f V.ED.... ........ 0,0-768,50 #102002f android:id/statusBarBackground}. Bottom edge 36 px below YouTubePlayerView's top edge. .
Here there is an image of the idea:
Picture of Android emulator, the user should introduce an url, clicks on Reproducir and plays the video from the url
If you are reinitilize the youtube video video view if already its been initialize thn first you need to release exising youtube view.
Please check below code
Specifically i've changed initialize part on Play button click
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (youTubePlayer != null) {
youTubePlayer.release();
}
youTubeView.initialize("AIzaSyDo9p_Qjy8XRBdFnVOaIx586MzHHLOUopw", (YouTubePlayer.OnInitializedListener) view.getContext());
}
});
Entire Activity code
public class AddVideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private YouTubePlayerView youTubeView;
private EditText urlTxtView;
private Button playButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_video);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_player_add);
urlTxtView = (EditText) findViewById(R.id.urlYoutube);
playButton = (Button) findViewById(R.id.buttonPlay);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (youTubePlayer != null) {
youTubePlayer.release();
}
youTubeView.initialize(Config.YOUTUBE_API_KEY, (YouTubePlayer.OnInitializedListener) view.getContext());
}
});
}
private YouTubePlayer youTubePlayer;
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
this.youTubePlayer = youTubePlayer;
String url = urlTxtView.getText().toString();
Log.d("1", url);
if (!wasRestored) {/// here videoid you need to pass not entire video URL
youTubePlayer.loadVideo(url);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "ERROR:" + result.toString(), Toast.LENGTH_LONG).show();
}
}
to load video you need to pass video id not video url.So with assumption tht in edit text video id will be pass or if url thn you will get the video id from url and thn video will be loaded
this.youTubePlayer = youTubePlayer;
String url = urlTxtView.getText().toString();
Log.d("1", url);
if (!wasRestored) {/// here videoid you need to pass not entire video URL
youTubePlayer.loadVideo(url);
}
And for below log
Log: W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to
unauthorized overlay on top of player. The YouTubePlayerView is
obscured by android.view.View{a21cb6f V.ED.... ........ 0,0-768,50
102002f android:id/statusBarBackground}. Bottom edge 36 px below YouTubePlayerView's top edge.
you can refer answer https://stackoverflow.com/a/29676512/1140237
in your case for this log... issue is with Application or Activity theme. Give No ActionBarTheme to resolve that error
I am really struggling with using the YouTubePlayerFragment in my application. My implementation looks like this:
private void loadYouTubeVideo(final YouTubeViewHolder h, final Content content) {
final YouTubePlayerFragment youTubePlayerFragment = YouTubePlayerFragment.newInstance();
FragmentTransaction transaction = ((DetailActivity) getContext()).getFragmentManager().beginTransaction();
transaction.add(R.id.fl_youtube, youTubePlayerFragment).commit();
final ViewTreeObserver observer = h.mRlYouTube.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
youTubePlayerFragment.initialize(YOUTUBE_PLAYER_API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if(!wasRestored) {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.loadVideo(content.getVideoId());
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e(getClass().getSimpleName(), "Error initializing YouTube Video with id ");
FragmentTransaction transaction = ((DetailActivity) getContext()).getFragmentManager().beginTransaction();
transaction.remove(youTubePlayerFragment);
}
});
}
});
}
The initialization is no problem, as a YouTubePlayer is displayed and the video is loaded. But it immediately stops after one second with the following message:
"YouTube video playback stopped due to the player's view being too small. The YouTubePlayerView is 0dp wide (minimum is 200dp) and 0dp high (minimum is 110dp)."
This is the XML layout with the FrameLayout, to which I add the YouTubePlayerFragment in the code above:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fl_youtube"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="200dp"
android:minHeight="110dp"
android:layout_marginBottom="5dp"
>
</FrameLayout>
I have no idea why the YouTubePlayer pretends to have width and height 0. When I log the size of the FrameLayout, its height is 607 and its width is 1080 px. Any ideas how to solve this problem?
It works for me: add android:configChanges="keyboardHidden|orientation|screenSize" in your AndroidManifest.xml activity description like this:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize">
or just
<activity android:name=".MyActivity"
android:configChanges="orientation">
via
I'm trying to get my app to play a YouTube video in a fragment, as This Official Documentation said that you can play YouTube videos in fragments.
But i can't get it done.
This is my code:
SingleArticleFragment:
public class SingleArticleFragment extends YouTubePlayerSupportFragment implements
YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "my api key";
public static final String YOUTUBE_VIDEO_CODE = "_oEA18Y8gM0";
// YouTube player view
private YouTubePlayerView youTubeView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.article, container, false);
return v;
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
youTubeView = (YouTubePlayerView) getActivity().findViewById(R.id.youtube_view);
// Initializing video player with developer key
youTubeView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
youTubePlayer.cueVideo(YOUTUBE_VIDEO_CODE);
// Hiding player controls
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(getActivity(), 1).show();
} else {
String errorMessage = "There was an error initializing the YouTubePlayer";
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
}
}
}
And this is article.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#color/white">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Cover Video -->
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp" />
<!-- Article Cover Photo -->
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/single_article_cover_photo"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:layout_weight=".14"/>
<!-- Article Title -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/single_article_title"
android:layout_gravity="center"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold"
android:padding="10dp"
android:layout_weight=".14"/>
</LinearLayout>
</ScrollView>
LogCat Errors:
android.view.InflateException: Binary XML file line #11: Error inflating class com.google.android.youtube.player.YouTubePlayerView
.
.
.
Caused by: java.lang.IllegalStateException: A YouTubePlayerView can only be created with an Activity which extends YouTubeBaseActivity as its context.
So what LogCat is telling me: YouTube only works in Activities!, but android documentation says otherwise.
Can anybody help here please ?
Thanks in advance.
You are mixing two different approaches.
You can either use a YouTubePlayerView together with a YouTubeBaseActivity or you can simply use a YouTubePlayerFragment/YouTubePlayerSupportFragment. Using a YouTubePlayerView inside a YouTubePlayerFragment is simply wrong.
If you use the first approach (view + activity), you need to place the view in your XML and then set the YouTubePlayer to play inside that view.
If you use the second approach, you simply need to load the fragment in an appropriate container, initialize the YouTubePlayer and play the video.
SOLUTION 1
Remove the YouTubePlayerView from your XML and your code and replace it with a FrameLayout that will contain the YouTubeSupportFragment. Then, use a ChildFragmentManager to load the YouTubeSupportFragment inside that FrameLayout.
SOLUTION 2
Simply make your Activity extend the YouTubeBaseActivity, leave everything else as it is.
I am trying to load a different video into a YoutubePlayer fragment when a button is clicked. My button has an onclick listener of testClick. When I click the button, I get the following exception: "UsupportedExeception: no views can be added on top of player". The initialize method also isn't being called when I initialize the new video from my onclick method. How can I a new YouTubeVideo to be loaded into the previously used YouTubePlayerFragment, and how I can get the initialize method to be called from my onClick method?
public class ExersizeListActivity extends Activity implements
YouTubePlayer.OnInitializedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exersize_list);
}
public void testClick(View v) {
//new YouTube Fragment to replace old one
YouTubePlayerFragment youTubePlayerFragment=YouTubePlayerFragment.newInstance();
youTubePlayerFragment.initialize(YoutubeAPIKey.API_KEY, this);
FragmentManager fragManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragManager.beginTransaction();
fragmentTransaction.replace(R.id.youtube_fragment, youTubePlayerFragment);
fragmentTransaction.commit();
}
#Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1) {
Log.e(null, "it bombed");
}
//not being called, and in current state would reinitialize with the same video
#Override
public void onInitializationSuccess(Provider arg0,
YouTubePlayer youtubePlayer, boolean arg2) {
youtubePlayer.cueVideo("YNKehLXpLRI");
}
}
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/randomizeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Randomize!"
android:layout_below="#+id/youtube_fragment"
android:onClick="testClick"/>
</RelativeLayout>
Rather than defining the fragment in the xml layout file with the <fragment> tag, define a FrameLayout container, necessary when changing fragments dinamically at runtime:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<FrameLayout
android:id="#+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/randomizeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Randomize!"
android:layout_below="#+id/youtube_fragment"
android:onClick="testClick"/>
</RelativeLayout>
You will need to add the first YouTubeVideoFragment in onCreate() with a FragmentTransaction, and when the user clicks the button, the code you already have in testClick() should work.