Problems using YouTubePlayerFragment, "the YouTubePlayerView is 0dp wide and 0dp high" - android

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

Related

Display several youtube video in an activity

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)

Android: Can't get YouTube Player API work inside of a fragment

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.

Android Landscape VideoView in portrait mode

I have an activity which should display a VideoView in landscape, but the activity itself must not be in landscape mode, so this is what i have.
<activity
android:name=".gui.VideoPlayer"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="portrait" >
</activity>
<?xml version="1.0" encoding="utf-8"?>
Activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<VideoView
android:id="#+id/myvideoview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center" />
</LinearLayout>
(The activity itself must remain in portrait mode because the device will be put in a case which covers the navigation and statusbars, but in landscape mode it wont cover them any more)
I know this is not the optimal answer but I had the same issue a while ago and found a pretty convenient workaround that might help you too.
Try to use a TextureView instead of VideoView because when you rotate it, the content inside rotates as well.
<TextureView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/my_texture_view"
android:rotation="90"
android:scaleX="1.8"
/>
Next you'll have to create a SurfaceTextureListener and set it to your view like below:
TextureView.SurfaceTextureListener mTextureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
Surface s = new Surface(surfaceTexture);
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(currentPageVideoUrl);
mMediaPlayer.setSurface(s);
mMediaPlayer.prepare();
}catch (Exception e){e.printStackTrace();}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
And now just set the listener to your TextureView:
mTextureView.setSurfaceTextureListener(mTextureListener);
All that's left to do is to call this to start the video:
mMediaPlayer.start();
BONUS:If you want to make more complex adjustments like adjusting the video aspect ratio You can check this library for more details.

YouTube Android fragment flickering

I'm embedding Youtube videos in my Android app using the official SDK. Problem is, the screen gets flickered(black color background for <0.5 seconds) each time a video is initialized.
XML:
<LinearLayout
android:id="#+id/youTube"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/cardui"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:visibility="visible"
tools:visibility="visible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginTop="5dp"
android:fontFamily="sans-serif-light"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:text="Watch video"
android:textAppearance="?android:attr/textAppearanceLarge" />
<!-- This is where Youtube fragment will be added -->
</LinearLayout>
Youtube Fragment Code:
public static class PlayerYouTubeFrag extends YouTubePlayerSupportFragment {
private String videoId;
public static PlayerYouTubeFrag newInstance(String videoId) {
PlayerYouTubeFrag playerYouTubeFrag = new PlayerYouTubeFrag();
Bundle bundle = new Bundle();
bundle.putString("videoId", videoId);
playerYouTubeFrag.setArguments(bundle);
return playerYouTubeFrag;
}
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
init();
return super.onCreateView(layoutInflater, viewGroup, bundle);
}
private void init() {
videoId = getArguments().getString("videoId");
initialize(youtubeKey, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youtubePlayer = youTubePlayer;
youtubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = b;
}
});
if (!b) {
youtubePlayer.cueVideo(videoId);
youtubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.d(TAG, "Player initialization failed");
}
});
}
}
And finally, adding the Fragment to layout:
mYoutubePlayerFragment = PlayerYouTubeFrag.newInstance(videoId);
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).add(R.id.youTube, mYoutubePlayerFragment).commit();
(findViewById(R.id.youTube)).setVisibility(View.VISIBLE);
Okay, this is because of a weird bug in YouTubeSupportFragment and I'm not the first to notice it. You can get around this, by adding an empty SurfaceView.
Read more here:
http://code.google.com/p/gdata-issues/issues/detail?id=4722
The bug is still present, the solution of just adding the SurfaceView with android:width and android:height 0dp didn't solve my problem. Instead, I had to add the SurfaceView in my Layout xml
<SurfaceView
android:id="#+id/surface"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
and had to set the visibility of the SurfaceView to visible in code while adding the youtube fragment.
findViewById(R.id.surface).setVisibility(View.VISIBLE);
getSupportFragmentManager().beginTransaction().replace(your_holder_id, youTubePlayerFragment).commit();
Hope this helps better.

Android YouTube API: Can't reinitialize YouTubePlayerFragment with new YouTube video

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.

Categories

Resources