How to play Youtube Video in a Fragment in ViewPager, Android - android

Now I am trying to play Youtube video in a fragment of ViewPager using YouTubePlayerSupportFragment.
I am using SmartFragmentStatePagerAdapter as a viewpager adapter.
But I got this error :
W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor android.support.v4.view.ViewPager{41a53898 VFED.... ......I. 0,84-480,730 #7f0c00b8 app:id/viewPager}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: 480, top: 0, right: -480, bottom: 376 (these should all be positive).
How can I solve this issue.
Regards
This is FragmentPageAdapter code
public class VideoPagerAdapter extends SmartFragmentStatePagerAdapter
{
private UserInfo usrInfo;
public VideoPagerAdapter(FragmentManager fragmentManager, UserInfo userInfo){
super(fragmentManager);
usrInfo = userInfo;
}
#Override
public Fragment getItem(int position) {
VideoDetailFragment videoDetailFragment = new VideoDetailFragment();
videoDetailFragment.video = usrInfo.videoList.get(position);
return videoDetailFragment;
}
#Override
public int getCount() {
return usrInfo.videoList.size();
}
}
and I have implemented code in VideoDetailFragment.
private YouTubePlayer mYoutubePlayer;
private YouTubePlayerSupportFragment mYoutubeFragment;
private void initYoutubeVideo(){
mYoutubeFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.youtube_layout, mYoutubeFragment).commit();
mYoutubeFragment.initialize(DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
mYoutubePlayer = youTubePlayer;
if (!b){
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.loadVideo(VIDEO_ID);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.d(TAG, "*** Youtube Player error : " + youTubeInitializationResult.toString());
String errorMessage = String.format(getString(R.string.error_youtube_player), youTubeInitializationResult.toString());
Utils.showAlert(mActivity, errorMessage);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (!isVisibleToUser && mYoutubePlayer != null) {
mYoutubePlayer.release();
}
if (isVisibleToUser && mYoutubeFragment != null) {
mYoutubeFragment.initialize(DEVELOPER_KEY, this);
}
}
and I have tested it in real device
06-08 19:02:47.012 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: Cannot load modern controls UI. Upgrade to the latest version of the Android YouTube API.
06-08 19:02:47.082 2562-2562/com.videofeed.tickit D/dalvikvm: DexOpt: couldn't find field Landroid/view/accessibility/CaptioningManager$CaptionStyle;.windowColor
06-08 19:02:47.082 2562-2562/com.videofeed.tickit W/dalvikvm: VFY: unable to resolve instance field 10579
06-08 19:02:47.082 2562-2562/com.videofeed.tickit D/dalvikvm: VFY: replacing opcode 0x52 at 0x0019
06-08 19:02:47.082 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: Forcefully created overlay:vtd#41fd4d28 helper:Lazy#41fd5898 view:null status: ...... {...}
06-08 19:02:47.372 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: Cannot load modern controls UI. Upgrade to the latest version of the Android YouTube API.
06-08 19:02:47.442 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: Forcefully created overlay:vtd#42c9fe20 helper:Lazy#42c9fe98 view:null status: ...... {...}
06-08 19:02:47.462 2562-2562/com.videofeed.tickit I/Choreographer: Skipped 40 frames! The application may be doing too much work on its main thread.
06-08 19:02:47.602 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: Cannot load modern controls UI. Upgrade to the latest version of the Android YouTube API.
06-08 19:02:47.692 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: Forcefully created overlay:vtd#42d8f2a8 helper:Lazy#42d8f320 view:null status: ...... {...}
06-08 19:02:51.912 2562-2604/com.videofeed.tickit D/dalvikvm: GC_FOR_ALLOC freed 15971K, 69% free 7899K/25052K, paused 35ms, total 37ms
06-08 19:02:58.202 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor android.support.v4.view.ViewPager{42c4a610 VFED.... ......ID 0,84-480,730 #7f0c00b8 app:id/viewPager}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: -480, top: 0, right: 480, bottom: 376 (these should all be positive).
06-08 19:02:58.222 2562-2562/com.videofeed.tickit W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor android.support.v4.view.ViewPager{42c4a610 VFED.... ......ID 0,84-480,730 #7f0c00b8 app:id/viewPager}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: 480, top: 0, right: -480, bottom: 376 (these should all be positive).
this is log in Android studio.
I have attached the screenshots.
This is the screenshot

It's not possible. Because YouTubePlayerView requires its activity to extend YoutubeBaseActivity. YouTubePlayerView provides limited functionality.

This answer maybe to late, but I found a possible solution.
I' run into similar problem, I also try to play multiple videos in viewpager.
If there's only one youtube fragment in viewpager, and it's ok, but when there's more then one, video won't play, and show that error message
YouTube video playback stopped due to unauthorized overlay on top of player.
First "unauthorized overlay" is not come from my current fragment which is on the
visible page of view pager. it come from the page that view pager create "next" to the current fragment.
View pager create pages before they are slide into visible window, so the youtube fragment are create before it is visible, and if you initialize that fragment, then youtube player detect that strange overlay error and stop the video, and the youtube player stop, even stop the video which is showing normally in the visible page.
In your case, you can see the error message
left: 480, top: 0, right: -480, bottom: 376
which the negative number is a window wide, so it's probability same as the issue I got.
So my solution
1. No't initialize the youtube at onCreate(), don't do the initialize before that fragment is the visible of the viewpager.
in my case, I use a interface between adapter and fragment, and in the parent page of the viewpager, add a OnPageChangeListener to viewpager, youtube fragment only initialize after viewpager's page is change to that youtube fragment.
page change > notify adapter > interface > youtubefragment > start initialize
After first step, first video should play normally even if there's 2 or more youtube fragment in viewpager, but when I swipe to 2nd page, video won't play and show the same error, so move to 2nd step
2. release youtube player when youtube fragment is slide to invisible part of view pager
the reason of 2nd video not playing is same, first page has a youtubeplayer and it out side the visible range, and it got an error message, which stop all youtubeplayer for a reason I don'y know why.
I use the same interface, when page is changed. adapter will use the interface to notify the youtube fragment which is slide away, to release youtubeplayer, and the interface implement like this, which mPlayer will be the youtubeplayer return by initialize method.
mInitializeListener = new InitializeListener() {
#Override
public void startVideo() {
initialize();
}
#Override
public void stopVideo() {
mPlayer.release();
}
};
there's still some questions I can't answer,
like why youtubeplayer in one pager will effect others..?
but when I did the changes at my adapter and fragment,
youtube video can play normally, hope this helps you
below are codes I use in my app
MediaFragmentViewPager adapter =
new MediaFragmentViewPager(getChildFragmentManager(), getActivity(), true);
List<MediaData> mediaDataList = new ArrayList<>();
adapter.setmResources(mediaDataList);
imageViewPager.setAdapter(adapter);
ViewPager.OnPageChangeListener pagerchangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
adapter.onPageChanged(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
imageViewPager.addOnPageChangeListener(pagerchangeListener);
pagerchangeListener.onPageSelected(0);
circlePageIndicator.setFillColor(getResources().getColor(R.color.colorAccent));
circlePageIndicator.setViewPager(imageViewPager);
Adapter
public class MediaFragmentViewPager extends FragmentStatePagerAdapter
implements MediaYoutubeFragment.MediaFullScreenListener {
protected List<MediaData> mResources;
private String apiKey = "your apiKey";
protected Map<Integer, MediaYoutubeFragment.InitializeListener> listenerMap = new HashMap<>();
private Context context;
private boolean isFullScreen;
public MediaFragmentViewPager(FragmentManager fm, Context context, boolean isFullScreen) {
super(fm);
this.context = context;
this.isFullScreen = isFullScreen;
}
public int currentPosition = -1;
#Override
public void startFullScreen() {
if (!isFullScreen){
MediaViewPagerActivity.startActivity(context, itemID, companyId, currentPosition);
}
}
#Override
public Fragment getItem(int position) {
if(mResources.get(position).isImage == true){
Log.i("tag3", "getItem image" + String.valueOf(position));
MediaImageFragment imageFragment = new MediaImageFragment();
imageFragment.setImageUrl(mResources.get(position).getImageResource().getImage1080p());
return imageFragment;
} else {
Log.i("tag3", "getItem video" + String.valueOf(position));
MediaYoutubeFragment youTubePlayerSupportFragment =
MediaYoutubeFragment.newInstance(mResources.get(position).getYoutubeUrl(), this);
listenerMap.put(position, youTubePlayerSupportFragment.getmInitializeListener());
return youTubePlayerSupportFragment;
}
}
public void onPageChanged(int position){
// current page it not null, realse youtubeplayer.
if(currentPosition != -1){
if(listenerMap.get(currentPosition) != null){
listenerMap.get(currentPosition).stopVideo();
}
}
// update current position
currentPosition = position;
Log.i("tag3", "onPageSelected " + String.valueOf(position));
//start loading video
MediaYoutubeFragment.InitializeListener listener = listenerMap.get(position);
if(listener != null){
Log.i("tag3", "startVideo " + String.valueOf(position));
listener.startVideo();
} else {
Log.i("tag3", "startVideo listener is null " + String.valueOf(position));
}
}
#Override
public int getCount() {
return mResources.size();
}
public List<MediaData> getmResources() {
return mResources;
}
public void setmResources(List<MediaData> mResources) {
this.mResources = mResources;
}
}
Youtube Fragment
public class MediaYoutubeFragment extends YouTubePlayerSupportFragment
implements YouTubePlayer.OnInitializedListener, YouTubePlayer.OnFullscreenListener {
private static final String KEY_VIDEO_ID = "VIDEO_ID";
public String apiKey = "yor apiKey";
private String mVideoId;
private YouTubePlayer mPlayer;
boolean mIsFullScreen;
private InitializeListener mInitializeListener;
private MediaFullScreenListener fullScreenListener;
public InitializeListener getmInitializeListener() {
return mInitializeListener;
}
public void setmInitializeListener(InitializeListener mInitializeListener) {
this.mInitializeListener = mInitializeListener;
}
public void setFullScreenListener(MediaFullScreenListener fullScreenListener) {
this.fullScreenListener = fullScreenListener;
}
public interface MediaFullScreenListener{
void startFullScreen();
}
public interface InitializeListener{
void startVideo();
void stopVideo();
}
public MediaYoutubeFragment(){
super();
mInitializeListener = new InitializeListener() {
#Override
public void startVideo() {
initialize();
}
#Override
public void stopVideo() {
if (mPlayer != null){
mPlayer.release();
}
}
};
}
private void initialize() {
initialize(apiKey, this);
}
public static MediaYoutubeFragment newInstance(String videoId, MediaFullScreenListener listener) {
MediaYoutubeFragment frag = new MediaYoutubeFragment();
Bundle args = new Bundle();
args.putString(KEY_VIDEO_ID, videoId);
frag.setArguments(args);
frag.setFullScreenListener(listener);
return frag;
}
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (getArguments() != null) {
mVideoId = getArguments().getString(KEY_VIDEO_ID);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
mPlayer = youTubePlayer;
mPlayer.setFullscreenControlFlags(FULLSCREEN_FLAG_CUSTOM_LAYOUT);
mPlayer.setOnFullscreenListener(this);
mPlayer.setFullscreen(false);
mPlayer.setShowFullscreenButton(true);
if (!wasRestored) {
// load your video
mPlayer.loadVideo(mVideoId);
}
else
{
mPlayer.play();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
public void onFullscreen(boolean fullscreen) {
Log.i("tag3", "onFullscreen" + String.valueOf(fullscreen));
mPlayer.setFullscreen(false);
fullScreenListener.startFullScreen();
}
}
I also handle full screen event with my own activity, and this viewpager contents not only youtube video, but also picture, so please ignore those part.
because I use view pager in fragment, so I use getChildFragmentManger, and I also use this adapter in Activity, but It creates another problem, that first video won't play at the first time viewpager isload , because the listener is call before getItem() in the adapter, So I made some changes that if adapter is first load(first youtube page is load at first time), listener will be call right after getItem return the fragment, other's are all the same.

So basically, the problem is that one of your videos is being loaded outside the visible screen causing the error of overlay.
In the case of a viewpager, the already loaded pages also load the video but those videos are not on screen causing the error.
SOLUTION (for viewpager):
Load one video at a time, i.e. the video to be played.
Do this by loading the video whenever the page is visible.

Related

YouTubeAndroidPlayerApi video not playing when id passed from recycleview onClick listener

When I pass youtube ID from recycleview onClick then it shows "This video is unavailable". But same video id works fine when I hard code it. I tried every possible way but could not find any solution. Please, help if anyone can.
This is the code for sending video key,
intent.putExtra("vUrl", adListModel.getUrl());
Getting the video key,
vUrl = getIntent().getStringExtra("vUrl");
Here, I am trying to load video from the video key,
youTubePlayerView.initialize(getResources().getString(R.string.google_api_key), new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
String videoId = vUrl;
Log.e("YOUTUBE_KEYS", videoId);
youTubePlayer.cueVideo(videoId);
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.play();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});

Embed YouTube live stream in android app

I'm trying to embed a live stream to android app. This code works perfect for other videos but when I put the URL code of live stream channel it is unable to load. It just keeps on loading. Suggest me something or is there any other API which I need to use for embedding live stream.
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.("5kbU-C0FxqA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
First video id out-of-date so you need to replace another one and check agein
Also i think your code should be like below
onCreate
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player);
youTubePlayerView.initialize(getString(R.string.google_developer_api_key), this);
OnInitializedListener
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(""); // your video id
youTubePlayer.play();
}
If you can't make it work with the YouTubePlayer API, you may consider using this alternative player: android-youtube-player.
This is all you need to do to play a live video:
Add the player to your XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.pierfrancescosoffritti.androidyoutubeplayer.player.YouTubePlayerView
android:id="#+id/youtube_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Initialize the player and play a video:
YouTubePlayerView youtubePlayerView = findViewById(R.id.youtube_player_view);
getLifecycle().addObserver(youtubePlayerView);
youtubePlayerView.getPlayerUIController().enableLiveVideoUI(true);
youtubePlayerView.initialize(new YouTubePlayerInitListener() {
#Override
public void onInitSuccess(#NonNull final YouTubePlayer initializedYouTubePlayer) {
initializedYouTubePlayer.addListener(new AbstractYouTubePlayerListener() {
#Override
public void onReady() {
String videoId = "2ccaHpy5Ewo";
initializedYouTubePlayer.loadVideo(videoId, 0);
}
});
}
}, true);
You can see a working example in the sample app.

How to play youtube video using Youtube Data api v3 Android?

Few days back I asked question Youtube API v2 not supported So as per youtube they have deprecated and all application and websites using this v2 api wont work at all. As they told to migrate to v3 there are any good example or documents for android. I have youtube url with video id. I just want to play videos using this api
You can use Video ID to play video...
Use YouTubePlayerView for that...
Let me show you a example which will makes everything clear....
below is a class which contains a YouTubePlayerView..
public class Play_youtube_video extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener
{
YouTubePlayerView video_player;
public static String VIDEO_ID = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// HIDE THE KEYBOARD
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
// TITLE BAR DISABLES AND FULL SCREEN IMPLEMENTATION
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_play_youtube_video);
try
{
System.out.println("youtube----VIDEO_ID---->" + VIDEO_ID);
video_player = (YouTubePlayerView) findViewById(R.id.youtubeplayerview_full_screen);
video_player.initialize(GlobalConstant.YOUTUBE_APIKEY, Play_youtube_video.this);
}
catch(Exception e)
{
e.printStackTrace();
}
catch(OutOfMemoryError e)
{
e.printStackTrace();
}
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result)
{
GlobalUtills.showToast("Youtube player not found.", Play_youtube_video.this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored)
{
if( !wasRestored )
{
player.loadVideo(Youtube_VIDEO_ID);
// player.setFullscreen(true);
// player.play();
}
}
public void closeYoutube(View v)
{
Play_youtube_video.this.finish();
}
}
I am answering this question because after some frustration it was not on android api related issue but Gdata youtube api i was using was returning wrong results.
Now its fixed.

Android Google Tag Manager v4 ContainerLoadedCallback

I am trying to implement Google Tag Manager by following the tutorial on this web page:
https://developers.google.com/tag-manager/android/v4/#init
But i cant seem to find what the ContainerLoadedCallback should do or where the source of this class is located. any help is greatly appreciated
What i currently have in my splash screen activity is the following:
PendingResult<ContainerHolder> pending =
App.getTagManager().loadContainerPreferNonDefault(C.Const.GTM_CONTAINER_ID,
R.raw.gtm_default_container);
// The onResult method will be called as soon as one of the following happens:
// 1. a saved container is loaded
// 2. if there is no saved container, a network container is loaded
// 3. the request times out. The example below uses a constant to manage the timeout period.
// The onResult method will be called as soon as one of the following happens:
// 1. a saved container is loaded
// 2. if there is no saved container, a network container is loaded
// 3. the request times out. The example below uses a constant to manage the timeout period.
pending.setResultCallback(new ResultCallback<ContainerHolder>() {
#Override
public void onResult(ContainerHolder containerHolder) {
ContainerHolderSingleton.setContainerHolder(containerHolder);
Container container = containerHolder.getContainer();
if (!containerHolder.getStatus().isSuccess()) {
Log.e("CuteAnimals", "failure loading container");
return;
}
ContainerHolderSingleton.setContainerHolder(containerHolder);
ContainerLoadedCallback.registerCallbacksForContainer(container);
containerHolder.setContainerAvailableListener(new ContainerHolder.ContainerAvailableListener() {
});
startMainActivity();
}
}, 2, TimeUnit.SECONDS);
It's implemented in their cuteanimals sample, you can find it in the sdk folder (assuming you have Google play services installed)
<SDK Dir>/extras/google/google_play_services/samples/tagmanager/cuteanimals/.../cuteanimals/SplashScreenActivity.java
Snippet:
private static class ContainerLoadedCallback implements ContainerHolder.ContainerAvailableListener {
#Override
public void onContainerAvailable(ContainerHolder containerHolder, String containerVersion) {
// We load each container when it becomes available.
Container container = containerHolder.getContainer();
registerCallbacksForContainer(container);
}
public static void registerCallbacksForContainer(Container container) {
// Register two custom function call macros to the container.
container.registerFunctionCallMacroCallback("increment", new CustomMacroCallback());
container.registerFunctionCallMacroCallback("mod", new CustomMacroCallback());
// Register a custom function call tag to the container.
container.registerFunctionCallTagCallback("custom_tag", new CustomTagCallback());
}
}
private static class CustomMacroCallback implements FunctionCallMacroCallback {
private int numCalls;
#Override
public Object getValue(String name, Map<String, Object> parameters) {
if ("increment".equals(name)) {
return ++numCalls;
} else if ("mod".equals(name)) {
return (Long) parameters.get("key1") % Integer.valueOf((String) parameters.get("key2"));
} else {
throw new IllegalArgumentException("Custom macro name: " + name + " is not supported.");
}
}
}
private static class CustomTagCallback implements FunctionCallTagCallback {
#Override
public void execute(String tagName, Map<String, Object> parameters) {
// The code for firing this custom tag.
Log.i("CuteAnimals", "Custom function call tag :" + tagName + " is fired.");
}
}

how to stop or restart a new instance of YouTubePlayerFragment, android, Google Youtube API for Android

in the code below I want to start a YouTubePlayerFragment object from the google's youtube API for Android. however it will only start when i first run the app. i have no control of the lifecycle of the fragment called YouTubePlayerFragment of Google's API, it extends Fragment, and is basically a fragment with a youtube player inside of it.
i have no ability to control this youtube player. the only way to get the youtubeplayer object and get control of the lifecycle of the player is to call the onInitializationSuccess() method, which you can't do because that method is called by the operating system. it is a callback method.
I can't figure out why I am getting all these problems with null pointer exceptions and other errors. basically I remove the video from visibility and later show the fragment visible only after the user clicks on a link in WebView where the substring "youtube" is contained in the URL. and then it would set the youtube fragment visible. i wanted to get the URL and start playing the video on that link.
if i try Fragment transaction remove() and add() methods I get null pointer and crashes.
and if i don't remove the fragment. then the next time the user clicks on a youtube link in webview it starts playing the same youtube video as before in an earlier link not the link just clicked. and it is starts the playback in the same position where it was left off before.
all I want to do is KILL this youtube API fragment and restart a new one.
how do I fix this problem?
public class MainActivity extends YouTubeFailureRecoveryActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
storedVideoUrl = "";
playTube = false;
setContentView(R.layout.fragments_demo);
pageView = (WebView) findViewById(R.id.webView1);
coverImage = (ImageView) findViewById(R.id.imageView1);
findViewById(R.id.youtube_fragment).setVisibility(View.INVISIBLE);
youTubePlayerFragment = (YouTubePlayerFragment)
getFragmentManager().findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, MainActivity.this);
coverImage.setVisibility(View.INVISIBLE);
pageView.loadUrl("http://www.example.com/");
WebSettings webSettings = pageView.getSettings();
//ebSettings.setJavaScriptEnabled(true);
WebViewClient mWebClient = new WebViewClient()
{
// Override page so it's load on my view only
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
storedVideoUrl = url;
playTube = true;
if ( url.contains("youtube") == true ){
// Load new URL Don't override URL Link
videoRoot = youTubePlayerFragment.getView();
videoUrl = url.substring(29, 40);
coverImage.setVisibility(View.VISIBLE);
videoRoot = youTubePlayerFragment.getView();
if(videoRoot==null){
videoRoot.setVisibility(View.INVISIBLE);
}else{
videoRoot.setVisibility(View.VISIBLE);
}
return true;
} else{
coverImage.setVisibility(View.INVISIBLE);
// Return true to override url loading (In this case do nothing).
return false;
// if return is true, do nothing. don't load url
}
}
};
pageView.setWebViewClient(mWebClient);
} // end onCreate
public YouTubePlayer.Provider getPlayer() {
return player;
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.loadVideo("videoUrl");
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK)
{
if (pageView.canGoBack()){
if((videoRoot.getVisibility())==View.VISIBLE){
coverImage.setVisibility(View.INVISIBLE);
videoRoot.setVisibility(View.INVISIBLE);
return true;
}else {
pageView.goBack();
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return null;
}
} // end fragment demo activity
You can't remove a fragment that has been declared in the XML layout you inflated. If you wish to add and remove fragments at will you have to create them and add them programatically.
That's probably why you get this when trying to remove the YouTubePlayerFragment.
if i try Fragment transaction remove() and add() methods I get null
pointer and crashes.
I'm not really familiar to Android Youtube API, but I will suggest you is to use something like this while adding your YoutubeFragment. Use this in your Fragment :
public static ColorPickerDialog newInstance(int num) {
ColorPickerDialog f = new ColorPickerDialog();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
and add your Fragment using something similar to this :
#SuppressLint("CommitTransaction")
public void showDialog() {
mDialogInstance++;
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment mColorPicker = ColorPickerDialog
.newInstance(mDialogInstance);
mColorPicker.show(ft, "dialog");
}
Check this if that will solve your problem.

Categories

Resources