Android Youtube API - is there an alternative for youtubeActivity - android

I want to implement youtube api, I noticed that I must have an activity inherited from the youTubeActivity class Is there another way to play YouTube video without having what youTubeactivity? I'd like to run it in a recyclerview if anyone has an example I'd love

youtube doc
Use YouTubePlayerView inside your recyclerview

You can use Youtube Fragment
YouTubePlayerSupportFragment mYouTubePlayerSupportFragment = new YouTubePlayerSupportFragment();
mYouTubePlayerSupportFragment.initialize(beanAppConfig.getData().getYoutubeDetail().getDeveloperkey(),
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean wasRestored) {
myouTubePlayer = youTubePlayer;
Log.e(TAG, "" + wasRestored);
if (!wasRestored) {
myouTubePlayer.loadVideo(youTubeVideoID);
myouTubePlayer.setPlayerStateChangeListener(LiveActivityYoutube.this);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
Log.e("onInitializationFailure", "");
}
});
mYouTubePlayerSupportFragment.setRetainInstance(true);
loadFragmentOverLay(mYouTubePlayerSupportFragment);
Load Fragment to FrameLayout
private void loadFragmentOverLay(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(frame_container_live.getId(), fragment);
transaction.commit();
}

Related

Minimizing/Maximizing youTube video in YouTubePlayerView

I have a container where I show a GIF video.On click of the GIF it opens the same video in YouTube. YouTubePlayerView has maximize and minimize icon, when I click on that video is just restarting instead of minimizing it and get back to the same container. I am not sure how to minimize the video which is playing in YouTubePlayerView.
I have created a separate Activity called YouTubeACtivity:
public class YoutubeActivity extends AppCompatActivity {
String shortCode = "";
public static void show(Activity activity, String shortCode)
{
Intent intent = new Intent(activity, YoutubeActivity.class);
intent.putExtra(Constants.YOUTUBE_VIDEO, shortCode);
activity.startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtubeplayer);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
shortCode = getIntent().getStringExtra(Constants.YOUTUBE_VIDEO);
YouTubePlayerFragment mYoutubePlayerFragment = new YouTubePlayerFragment().newInstance();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.youtubeContainer, mYoutubePlayerFragment);
ft.commit();
if (mYoutubePlayerFragment != null) {
mYoutubePlayerFragment.initialize(getResources().getString(R.string.google_api_key), new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) {
//youTubePlayer.setFullscreen(true);
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE| YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
// youTubePlayer. setShowFullscreenButton(false);
youTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean fullscreen) {
// onBackPressed();
}
});
Log.e("shortcode ", "reached" + shortCode);
if (shortCode != null) {
if (restored) {
youTubePlayer.play();
} else {
youTubePlayer.loadVideo("" + shortCode + "");
}
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e("youtube initialization ", "initialisation fails");
}
});
}
}
}
The GIF video is showing in a FrameLayout which implements SurfaceHolder callback.
I just wanted to know is there anyway we can make minimize the video and comeback to the container layout.
First I suggest to use the player object to go or exit fullscreen
youtubeplayer.setFullScreen(true/false);
then add config changes in manifest of the activity containing the container
android:configChanges="orientation|screenSize|keyboardHidden|screenLayout"
as far as i can understand your problem your activity is getting restarted

YoutubePlayerSupportFragment inside Viewpager

I have about 5 different videos from youtube and I want to put them into viewpager to slide them. Is there any solution for this with explanation, because I searched here and at different sites, but can't find something useful. Thank you for attention
You have to call YouTubePlayerSupportFragment.reset() on the old YouTubePlayer when the ViewPager is switched and then YouTubePlayerSupportFragment.initialize(). This requires responding to the TabLayout's onTabSelected events which cant use .setupWithViewPager (which swallows both the ViewPager and TabLayouts view change events). This is roughly what's needed in the adapter (initialisePlayer and shutDownPlayer are called in response to tab changes, in the fragment that sets up the adapter, ViewPager and TabLayout):
private SparseArray<YouTubePlayerSupportFragment> fragments = new SparseArray<>(3);
private SparseArray<YouTubePlayer> players = new SparseArray<>(3);
#Override
public android.support.v4.app.Fragment getItem(final int position) {
YouTubePlayerSupportFragment fragment = new YouTubePlayerSupportFragment();
fragments.put(position, fragment);
return fragment;
}
public void initialisePlayer(final int position) {
YouTubePlayerSupportFragment fragment = fragments.get(position);
fragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(final YouTubePlayer.Provider provider, final YouTubePlayer youTubePlayer, final boolean b) {
players.put(position, youTubePlayer);
youTubePlayer.cueVideo(getVids()[position]);
}
#Override
public void onInitializationFailure(final YouTubePlayer.Provider provider, final YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
public void shutDownPlayer(int position) {
YouTubePlayer player = players.get(position);
if (player == null) {
return;
}

Multiple YouTubePlayerFragment's in a ViewPager

I am working on an App which shows a bunch of contents and each content is a View managed by a ViewPager. Some of these contents may include a youtube video. For that, I place an instance of YouTubePlayerFragment inside the page. It works fine and I see videos, but the issue is this:
Let's assume there are three pages in the ViewPager, namely P1, P2, and P3. Each page contains a youtube video, V1, V2, and V3 respectively. If I am on page P2 and swipe left and then back to P2, I see the content of page P2, but the loaded video is V1. If I swipe right to P3 and back to P2, then the content of P2 is correct, except that it shows V3.
I added an extra line in onLoaded(String s) in my listener for testing purpose, and I detected that the Video ID that I give to player.cueVideo() as input differs from 's' which is the Video ID that is loaded to the player and this is basically the problem. But I am not sure why this happens. Below is all the relevant part of the code:
protected void addYourTubeFragment() {
youtubeVideoID = getYoutubeVideoID();
FragmentTransaction fragmentTransaction = ((Activity) getContext()).getFragmentManager().beginTransaction();
YouTubePlayerFragment youtubeFragment = YouTubePlayerFragment.newInstance();
fragmentTransaction.add(R.id.video_entity_layout, youtubeFragment);
fragmentTransaction.commit();
youtubeFragment.initialize(Util.DEVELOPER_KEY, this);
}
public void onInitializationSuccess(Provider provider, YouTubePlayer ytPlayer, boolean wasRestored) {
if ( !wasRestored ) {
YouTubePlayer player = ytPlayer;
Log.d(TAG, "Card ID: " + card.getId() + " Youtube Video ID: " + videoLinkToPlay);
player.cueVideo(youtubeVideoID);
player.setOnFullscreenListener(new OnFullscreenListener() {
public void onFullscreen(boolean full) {
playingFull = full;
}
});
player.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onLoading() {
}
#Override
public void onLoaded(String s) {
if (!youtubeVideoID.equals(s)) {
DialogBuilder.showSimpleAlert(getContext(), "ERROR", "This is different from the original Video ID");
}
}
#Override
public void onAdStarted() {
}
#Override
public void onVideoStarted() {
TrackingUtil.logTimed(TrackingUtil.EVENT_WATCHES_CARD_VIDEO);
}
#Override
public void onVideoEnded() {
FlurryAgent.endTimedEvent(TrackingUtil.EVENT_WATCHES_CARD_VIDEO);
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
}
});
}
}
Can anyone help me figure this out? Is it an Android/YourtubePlayer issue? or is it something I am not doing right?

How to play a video with the YouTube API using YouTubePlayerFragment?

I'm trying to play video in my Fragment. However, I cannot get it to work. If I'm extending 'YoutubeFailureRecovery' I get:
09-06 21:56:40.472: E/AndroidRuntime(4946): Caused by: java.lang.IllegalStateException: A YouTubePlayerView can only be created with an Activity which extends YouTubeBaseActivity as its context.
This is my .xml:
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/player"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
And this is the class:
public class YoutubeFragment extends YoutubeFailureRecovery {
YouTubePlayer player;
YouTubePlayerView playerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.detailview, container, false);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
playerView = (YouTubePlayerView)getActivity().findViewById(R.id.player);
playerView.initialize(DataHolder.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
// TODO Auto-generated method stub
player.cueVideo("nCgQDjiotG0");
}
#Override
protected Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return playerView;
}
}
public abstract class YoutubeFailureRecovery extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener{
I just don't know what to do. I tried to extend my Fragment class with 'YoutubePlayerSupportFragment', tried to add a video-like fragment in XML, but nothing is working (error inflating). Maybe someone has some experience with using YouTube API in Fragment?
The YouTubePlayerView only works with an Activity that extends
YouTubeBaseActivity.
If you want to use Fragments you have to use the YoutubePlayerFragment / SupportFragment.
You can for example create your custom Fragment that inherits from YoutubePlayerSupportFragment:
public class VideoFragment extends YouTubePlayerSupportFragment {
public VideoFragment() { }
public static VideoFragment newInstance(String url) {
VideoFragment f = new VideoFragment();
Bundle b = new Bundle();
b.putString("url", url);
f.setArguments(b);
f.init();
return f;
}
private void init() {
initialize("yourapikey", new OnInitializedListener() {
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) { }
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(getArguments().getString("url"));
}
}
});
}
}
In code it could look like this:
VideoFragment f = VideoFragment.newInstance("your-video-url");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, f).commit();
The "fragment_container" in this case should be an empty FrameLayout.

YouTubePlayerFragment lifecycle in a DialogFragment

I am trying to embed a YouTubePlayerFragment into a DialogFragment. I am able to start the dialog one time and show the YouTubePlayer in it, but the second time it always crashes (no matter what I do). I think it is a lifecycle problem, which I simply don't understand.
I am using AndroidAnnotations and the problem is that the view of the DialogFragment is always created in the onCreateView method, which is generated by AndroidAnnotations.
Does anyone know how to handle the lifecycle of a DialogFragment in this case?
This is the generated code from AndroidAnnotations:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
contentView_ = super.onCreateView(inflater, container, savedInstanceState);
if (contentView_ == null) {
contentView_ = inflater.inflate(layout.video_fragment, container, false);
}
return contentView_;
}
This is what I have so far:
public class VideoFragmentDialog extends DialogFragment implements YouTubePlayer.OnInitializedListener {
private static final String DEVELOPER_KEY = "secret";
private String videoUrl;
#FragmentById(R.id.youTubePlayerFragment)
YouTubePlayerFragment youTubePlayerFragment;
#AfterViews
void initializeYouTubePlayer() {
youTubePlayerFragment.setRetainInstance(true);
youTubePlayerFragment.initialize(DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.cueVideo(videoUrl);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
//To change body of implemented methods use File | Settings | File Templates.
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
}
This is the stacktrace:
Caused by: java.lang.IllegalArgumentException: Binary XML file line #10: Duplicate id 0x7f0a0281, tag null, or parent id 0x7f0a0280 with another fragment for com.google.android.youtube.player.YouTubePlayerFragment
at android.app.Activity.onCreateView(Activity.java:4248)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:673)
I guess it's because you are using a fragment inside a fragment (Nested fragments) without using getChildFragment()
Look here for an example how to do it : nested fragments

Categories

Resources