initialize youtube player fragment within a fragment - android

I am trying to initialize youtubeplayer fragment within a fragment. I successfully implemented the fragment within an activity but getting problem to initialize it in a fragment.
the code snippet for activity is as below
public class MainActivity extends AppCompatActivity {
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeYoutubePlayer();
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
//print or show error if initialization failed
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
To convert this code into fragment, I tried this
public class Welcome extends Fragment {
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private YouTubePlayer youTubePlayer;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_welcome, container, false);
initializeYoutubePlayer();
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
private void getSupportFragmentManager() {
}
}
but getting error in finding the fragment layout. Can somebody guide me how to do this in fragment? The layout for Welcome fragment is as follows
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FCFDFF"
tools:context="com.currentmedia.channelslayout.Welcome">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:background="#FF0000"
app:title="Punjabi News Live"
app:titleTextColor="#FFFFFF" />
<!-- Youtube Player Fragment -->
<LinearLayout
android:id="#+id/linearlayout01"
android:layout_width="fill_parent"
android:layout_height="220dp"
android:layout_below="#id/adView"
android:layout_marginTop="2dp"
android:background="#ccc"
android:orientation="vertical">
<fragment
android:id="#+id/youtube_player_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragmentX"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

In your layout, instead of using a < fragment > you should use a < FragmentContainerView > and replace the fragment in your activity using transaction.
Here is a tutorial if you're new with manipulating fragment in 2020:
FragmentContainerView explanation

Related

YouTubePlayerSupportFragment inside fragment

I have a fragment and I want to play YouTube video inside fragment. For this I have follow the following steps:
Created project on Google console
Generate Key
Download and install YouTubeAndroidPlayerApi.
Create a simple fragment
Add YouTubePlayerSupportFragment
Write the code in java file
When I run App, got an error message:
Caused by: android.view.InflateException: Binary XML file line #10: 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.
Code of XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.youtube.player.YouTubePlayerView
android:name="com.google.android.youtube.player.
YouTubePlayerSupportFragment"
android:id="#+id/YoutubePlayer"
android:layout_width="match_parent"
android:layout_height="240dp"
android:layout_marginTop="20dp"/>
</LinearLayout>
Code of Java File
public class TopicYoutubeFragment extends Fragment implements YouTubePlayer.OnInitializedListener {
private YouTubePlayer youtubeplayer;
private static final String YoutubeDeveloperKey = "AIzaSyAp8uMTh0VnYI";
private String YoutubeURL, youtubeID;
private String TopicName;
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView ypv;
public TopicYoutubeFragment() {
}
public static TopicYoutubeFragment newInstance(String YoutubeURL, String TopicName) {
TopicYoutubeFragment fragment = new TopicYoutubeFragment();
Bundle args = new Bundle();
args.putString("YoutubeURL", YoutubeURL);
args.putString("TopicName", TopicName);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
YoutubeURL = getArguments().getString(YoutubeURL);
TopicName = getArguments().getString(TopicName);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.topicyoutubefragment, container, false);
ypv = view.findViewById(R.id.YoutubePlayer);
ypv.initialize(YoutubeDeveloperKey, this);
youtubeID = "F7xdbsjFGtU";
return view;
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
if (youtubeID != null)
youTubePlayer.cueVideo(youtubeID); // Plays https://www.youtube.com/watch?v=F7xdbsjFGtU
else
Toast.makeText(getActivity(), "No Video is available for this Topic", Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
}
}
}

YouTubePlayer api issue

I play video in MainActivityand video is playig fine. While playing video, if I open the same activity another time and come back to previous MainActivity youtube progressbar keeps turning and nothing happens. I read the documentation and couldn't find anything related this problem. Indeed, the documentation is very old (updated in 2015), and YouTubeAndroidPlayerApi library was updated in 2017. Guide me to right direction.
MainActivity.java
public class MainActivity extends YouTubeBaseActivity
implements YouTubePlayer.OnInitializedListener {
private String YOUTUBE_API_KEY = "api_key";
private YouTubePlayerView youtubePlayerView;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
youtubePlayerView = findViewById(R.id.youtubePlayer);
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.w("youtube_activity", "onInitialization success");
youTubePlayer.loadVideo("0KSOMA3QBU0");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(this, "Initialization failure", Toast.LENGTH_SHORT);
}
public void onClick(View view) {
startActivity(new Intent(this, MainActivity.class));
}
}
layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="onClick"
android:text="Button" />
</LinearLayout>
Found solution with releasing YouTubePlayer when going to another youtubeplayeractivity. When came back to previous youtubeplayeractivity reninitialized YouTubePlayerView.
public void onClick(View view) {
youTubePlayer.release();
startActivity(new Intent(this, MainActivity.class));
}
#Override
protected void onRestart() {
super.onRestart();
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}

How to play youtube video on top of other fragment in android

I am trying to play youTube video's within an existing fragment on runtime using other fragment. I try to follow the fragment within other fragment. But I am not able to see videos only audio is playing with the previous fragment view. Please help me out. I queried about 200 pages but nothing worked for me. Any help will be appreciated.
Here is my my_fragment.xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentOpponents"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:keepScreenOn="true">
<android.support.v7.widget.RecyclerView
android:id="#+id/opponents"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:numColumns="3" />
<FrameLayout
android:id="#+id/child_fragment"
android:layout_width="250dp"
android:layout_height="250dp">
</FrameLayout>
</RelativeLayout>
Code for YoutubeFragment:
public class YoutubeFragment extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
private static final String KEY_VIDEO_ID = "KEY_VIDEO_ID";
private String mVideoId;
//Empty constructor
public YoutubeFragment() {
}
/**
* Returns a new instance of this Fragment
*
* #param videoId The ID of the video to play
*/
public static YoutubeFragment newInstance(final String videoId) {
final YoutubeFragment youTubeFragment = new YoutubeFragment();
final Bundle bundle = new Bundle();
bundle.putString(KEY_VIDEO_ID, videoId);
youTubeFragment.setArguments(bundle);
return youTubeFragment;
}
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
final Bundle arguments = getArguments();
if (bundle != null && bundle.containsKey(KEY_VIDEO_ID)) {
mVideoId = bundle.getString(KEY_VIDEO_ID);
} else if (arguments != null && arguments.containsKey(KEY_VIDEO_ID)) {
mVideoId = arguments.getString(KEY_VIDEO_ID);
}
initialize(Consts.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) {
if (mVideoId != null) {
if (restored) {
youTubePlayer.play();
} else {
youTubePlayer.loadVideo(mVideoId);
}
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show();
} else {
//Handle the failure
Toast.makeText(getActivity(), R.string.error_init_failure, Toast.LENGTH_LONG).show();
}
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString(KEY_VIDEO_ID, mVideoId);
}
}
I am using this code to call a fragment on runtime,
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = YoutubeFragment.newInstance("q8_o4W9ZyZk");
fragmentTransaction.add(R.id.child_fragment, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
As you are using nested fragments, use getChildFragmentManger() method instead getSupportFragmentManager
Here and here there is more info
Hope it helps!

show Action bar in YouTube activity

I using youtube api and playing youtube video using below tag in xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.aspire.urdu.toddlers.poems.VideoListingActivity">
<include
android:id="#+id/toolbar"
layout="#layout/action_bar" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:hardwareAccelerated="true" />
</LinearLayout>
and i am using this code in activity.
public class VideoPlayerActivity extends YouTubeBaseActivity{
YouTubePlayer YTplayer;
YouTubePlayerView youTubePlayerView;
private String videoLink = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoLink = getIntent().getStringExtra("link");
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(getResources().getString(R.string.you_tube_api_key), new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
YTplayer = youTubePlayer;
YTplayer.setShowFullscreenButton(false);
YTplayer.loadVideo(videoLink);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getApplicationContext(), ""+youTubeInitializationResult.name(), Toast.LENGTH_LONG).show();
}
});
}
}
but when video is playing it is showing on full screen..
What i need
i just need to display action with back button enabled Thanks.

Multiple Youtube players in one activity

I'm using the Youtube Android Player API as outlined here: https://developers.google.com/youtube/android/player/
However, I can't get more than one video into my activity at once. I tried simply putting two YouTubePlayerViews into the activity like so:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/view_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/view_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package com.example.multidemo;
import android.os.Bundle;
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.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((YouTubePlayerView) findViewById(R.id.view_one)).initialize("API key", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1, boolean arg2) {
arg1.cueVideo("RpwoN_XlN6Y");
}
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
}
});
((YouTubePlayerView) findViewById(R.id.view_two)).initialize("API key", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1, boolean arg2) {
arg1.cueVideo("jkk2mMq2x8E");
}
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
}
});
}
}
When I try this, the first view just comes up black, while the second video loads. If I comment out the code in onCreate() for the second video, then just the first video will load.
Is there any way to get multiple YouTubePlayerViews into the same activity?
This might be too late for an answer, but i had the same issue recently. Hope this helps to someone who might face the same issue. The trick to get around this is Using YoutubePlayerFragments instead. As long as you use Youtube player view, you'll hit the limit imposed of only one initialization done out of multiple requests. Typically the initialization succeeds for last one.
I ended up dynamically generating gridlayout and placing my (dynamically generated)fragment's view in each of the cells. And then i initialize the instance of player inside onResume. Once initialization is sucessful, you'll get a handle to player, and you can cue different videos randomly on fragments.
I'll just paste the code that will give you an idea about how i am constructing fragments and doing initialization:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mLogger.i("Preparing Youtube view for fragment ..");
mFragmentHeight = CustomFragment.getFragmentHeight(mNumScreens,mNumColumns);
mFragmentWidth = CustomFragment.getFragmentWidth(mNumColumns);
LinearLayout linearLayout = new LinearLayout(getActivity());
GridLayout.LayoutParams gridparams = new GridLayout.LayoutParams();
gridparams.rowSpec = GridLayout.spec(mGridRow);
gridparams.columnSpec = GridLayout.spec(mGridColumn);
gridparams.height = mFragmentHeight;
gridparams.width = mFragmentWidth;
linearLayout.setLayoutParams(gridparams);
if(YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(getActivity())==
YouTubeInitializationResult.SUCCESS)
{
View ytView = super.onCreateView(inflater, container, savedInstanceState);
linearLayout.addView(ytView);
}
else
mLogger.e("Either youtube service is down," +
" or you dont have required version of YouTube app .." +
"\nYouTube Fragment will not work as expected..");
mView = linearLayout;
mLogger.i("Preparation youtube view for fragment complete..");
return mView;
}
#Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1)
{
mLogger.e("Youtube player initialization failed");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored)
{
mLogger.i("You tube player initialized successfully.. will attempt to stream..");
mYoutubePlayer = player;
setListeners();
try
{
if (!wasRestored)
{
if(mPlayListFragment)
player.loadPlaylist(getResourceID());
else
player.loadVideo(getResourceID());
}
}
catch(Exception e)
{
mLogger.e("Error loading playlist/video .."+e);
}
}
public void onResume()
{
super.onResume();
initialize(API_KEY, this);
}

Categories

Resources