34

My Activity extends another activity and consists of navigation drawer where each item opens a new fragment.I want to integrate Youtube to one of the fragment..Previously i used YouTubePlayerView to integrate Youtube to activity but here it is required in fragment.I searched on net and found YouTubePlayerFragment to integrate youtube to fragment. But when i searched in tutorials I found that even by using YouTubePlayerFragment we are extending YouTubeBaseActivity .These are the examples.. http://android-coding.blogspot.in/2013/04/example-to-use-youtubeplayerfragment-of.html http://android-er.blogspot.in/2013/06/example-to-use-youtubeplayerfragment-of.html

I failed to understand how to use YouTubePlayerFragment such that my class extends Fragment rather than YouTubeBaseActivity which is required in my project..As u can see below my class extends another activity and consists of navigation drawer in which fifth option opens YouTube Fragment.I want to play Youtube video inside this fragment..I am giving brief layout how my classes are-

public class LandingActivity extends BaseGActivity {
.
.
.
.


public void selectDrawerItem(int position) {

        Bundle args = new Bundle();

        switch (position) {
            case 0:
                currentFragment = new HomeFragment_();
                args.putString(G.General.MEDIA_TYPE_KEY, G.General.MEDIA_TYPE_ALL);
                GApplication.getInstance().stopGPlayer();
                break;
            case 1:
                currentFragment = new HomeFragment_();
                args.putString(G.General.MEDIA_TYPE_KEY, G.General.MEDIA_TYPE_PHOTO);
                GApplication.getInstance().stopGPlayer();
                break;
//
            case 2:
                currentFragment = new HomeFragment_();
                args.putString(G.General.MEDIA_TYPE_KEY, G.General.MEDIA_TYPE_AUDIO);
                GApplication.getInstance().stopGPlayer();
                break;

            case 3:
                currentFragment = new HomeFragment_();
                args.putString(G.General.MEDIA_TYPE_KEY, G.General.MEDIA_TYPE_VIDEO);
                GApplication.getInstance().stopGPlayer();
                break;
            case 4:
                currentFragment = new HomeFragment_();
                args.putString(G.General.MEDIA_TYPE_KEY, G.General.MEDIA_TYPE_MEME);
                GApplication.getInstance().stopGPlayer();
                break;
            case 5:
                currentFragment = new YoutubeFragment();
            default:
                currentFragment = new HomeFragment_();
                args.putString(G.General.MEDIA_TYPE_KEY, G.General.MEDIA_TYPE_ALL);
                GApplication.getInstance().stopGPlayer();
                break;
        }

        currentFragment.setArguments(args);
        FragmentManager frgManager = getFragmentManager();
        frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
                .commit();

        mDrawerList.setItemChecked(position, true);
        setTitle(dataList.get(position).getItemName());
        mDrawerLayout.closeDrawers();
    }


    public class YoutubeFragment extends Fragment implements YouTubePlayer.OnInitializedListener{
        private FragmentActivity myContext;

        private YouTubePlayer YPlayer;
        private static final String YoutubeDeveloperKey = "xyz";
        private static final int RECOVERY_DIALOG_REQUEST = 1;
        @Override
        public void onAttach(Activity activity) {

            if (activity instanceof FragmentActivity) {
                myContext = (FragmentActivity) activity;
            }

            super.onAttach(activity);
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.activity_you_tube_api, container, false);

            YouTubePlayerView youTubeView = (YouTubePlayerView) rootView.findViewById(R.id.youtube_view);
            youTubeView.initialize(YoutubeDeveloperKey, (YouTubePlayer.OnInitializedListener) myContext);
            return rootView;
        }
        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider,
                                            YouTubeInitializationResult errorReason) {
            if (errorReason.isUserRecoverableError()) {
                errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
            } else {
                String errorMessage = String.format(
                        "There was an error initializing the YouTubePlayer",
                        errorReason.toString());
                Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == RECOVERY_DIALOG_REQUEST)
            {

                getYouTubePlayerProvider().initialize(YoutubeDeveloperKey, this);
            }
        }



        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                            YouTubePlayer player, boolean wasRestored) {
            if (!wasRestored) {
                YPlayer = player;
                YPlayer.setFullscreen(true);
                YPlayer.loadVideo("2zNSgSzhBfM");
                YPlayer.play();
            }
        }

    }

YouTubeFragment.java

public class YoutubeFragment extends Fragment implements
        YouTubePlayer.OnInitializedListener {
    private FragmentActivity myContext;

private YouTubePlayer YPlayer;
private static final String YoutubeDeveloperKey = "xyz";
private static final int RECOVERY_DIALOG_REQUEST = 1;

@Override
public void onAttach(Activity activity) {

    if (activity instanceof FragmentActivity) {
        myContext = (FragmentActivity) activity;
    }

    super.onAttach(activity);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.activity_you_tube_api, container, false);

    YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();

    youTubePlayerFragment.initialize("DEVELOPER_KEY", new YouTubePlayer.OnInitializedListener() {


    });
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();
    return rootView;

}
    @Override
    public void onInitializationSuccess (YouTubePlayer.Provider provider, YouTubePlayer
    youTubePlayer,boolean b){
        if (!b) {
            YPlayer = youTubePlayer;
            YPlayer.setFullscreen(true);
            YPlayer.loadVideo("2zNSgSzhBfM");
            YPlayer.play();
        }
    }

    @Override
    public void onInitializationFailure (YouTubePlayer.Provider
    provider, YouTubeInitializationResult youTubeInitializationResult){

    }
}

layout

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
        android:id="@+id/youtube_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Error-

Error:(64, 101) error: <anonymous com.pc.gi.ui.fragment.YoutubeFragment$1> is not abstract and does not override abstract method onInitializationFailure(Provider,YouTubeInitializationResult) in OnInitializedListener
Android Developer
  • 9,157
  • 18
  • 82
  • 139
  • I've implemented a youtube video player in my app recently. My first try was using YoutubePlayerFragment, but its API is a little bit unpractical and it didn't provide very "smooth" user experience... so I tried Youtube iframe API (https://developers.google.com/youtube/iframe_api_reference) inside a WebView. Android WebView does not support all the HTML5 features, so you need to do some stuff by yourself... but this (https://code.google.com/p/html5webview/) is a good place to start. Final result is worth it. – Luboš Staráček Oct 20 '14 at 12:43

2 Answers2

80

First extend your Activity as normal

 class YourActivity extends Activity...

in Layout file put the below lines

<fragment
  android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
  android:id="@+id/youtube_fragment"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"/>

Then in your Activity you can create its instance using below line in your onCreareView method of your Fragment.

YouTubePlayerSupportFragment youTubePlayerFragment = (YouTubePlayerSupportFragment) getActivity().getSupportFragmentManager()
                    .findFragmentById(R.id.youtube_fragment);

or you can declare a FrameLayout in your xml and then initiate the YouTubeSupportFragment using below lines

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/youtube_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:visibility="visible" />

</RelativeLayout>

Code in your onCreateView

 YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();

    youTubePlayerFragment.initialize("DEVELOPER_KEY", new OnInitializedListener() {

        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {

            if (!wasRestored) {
                YPlayer = player;
                YPlayer.setFullscreen(true);
                YPlayer.loadVideo("2zNSgSzhBfM");
                YPlayer.play();
            }

        }

        @Override
        public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
            // TODO Auto-generated method stub

        }
    });
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();

The key thing here is to use YouTubePlayerSupportFragment instead of YouTubePlayerFragment.

Hope this helps.

Here is your Fragment

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.OnInitializedListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
import com.ismart.omanapp.R;

public class YoutubeFragment extends Fragment {
    private FragmentActivity myContext;

    private YouTubePlayer YPlayer;
    private static final String YoutubeDeveloperKey = "xyz";
    private static final int RECOVERY_DIALOG_REQUEST = 1;

    @Override
    public void onAttach(Activity activity) {

        if (activity instanceof FragmentActivity) {
            myContext = (FragmentActivity) activity;
        }

        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_you_tube_api, container, false);

        YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();

        youTubePlayerFragment.initialize("DEVELOPER_KEY", new OnInitializedListener() {

            @Override
            public void onInitializationSuccess(Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
                if (!b) {
                    YPlayer = youTubePlayer;
                    YPlayer.setFullscreen(true);
                    YPlayer.loadVideo("2zNSgSzhBfM");
                    YPlayer.play();
                }
            }

            @Override
            public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
                // TODO Auto-generated method stub

            }
        });

    }
}
Sunny
  • 14,522
  • 15
  • 84
  • 129
  • 1
    Hii..i want to play youtube video inside fragment..my activity consists of navigation drawer on which i want when i'll click on fifth item it opens a fragment in which youtube video is played.If i place this code inside activity will it play youtube video on clicking on fifth item in navigation drawer..or it will start playing youtube video inside activity only?What code should i place inside class that extends fragment..please read my question again..thanku for ur time.. – Android Developer Oct 20 '14 at 06:30
  • 3
    Actually you want YoutubeFragment inside Your Fragments. You need to use `getChildFragmentManager()` instead of `getSupportedFragmentManager();` – Sunny Oct 20 '14 at 10:00
  • 1
    You should use my second method. i.e create an xml file and place a frameLayout inside it and use the code I wrote above in your fragment `onCreateView`. – Sunny Oct 20 '14 at 10:03
  • 1
    Thanku for the help..+1 for ur answer..plzz check out updated question above with updated code of YouTubeFragment.java and xml file..i have also listed the error i am getting..let me know where i am going wrong.. – Android Developer Oct 20 '14 at 11:12
  • Hi, Just use `public class YoutubeFragment extends Fragment {` do not implement the `YouTubePlayer.OnInitializedListener` in your fragment. You already implemented it in anonymous class. – Sunny Oct 20 '14 at 11:26
  • i got following error at transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit(); -Error:(87, 20) error: no suitable method found for add(int,YouTubePlayerSupportFragment) method FragmentTransaction.add(Fragment,String) is not applicable (argument mismatch; int cannot be converted to Fragment) method FragmentTransaction.add(int,Fragment) is not applicable (argument mismatch; YouTubePlayerSupportFragment cannot be converted to Fragment) – Android Developer Oct 20 '14 at 11:30
  • Please check that you have imported correct FragmentTransaction. i.e `android.support.v4.app.FragmentTransaction`. It's working on my side. – Sunny Oct 20 '14 at 11:36
  • Ok. I wrote the code for you. see the edit in my answer. – Sunny Oct 20 '14 at 11:43
  • According to my project i am using android.app.Fragment so i have to use android.app.FragmentTransaction – Android Developer Oct 20 '14 at 11:56
  • So cool :) –  Jun 11 '15 at 22:07
  • @sunny i think you can help me as well.. I have a activity that extends AppCompactActivity and also it needs to extend YoutubeBaseActivity but java does not let you do so.Is there any possible way in which i can achieve the both ? I need your help plz – bhaskar Mar 01 '16 at 03:49
  • Hi, I'm looking for the URL of the video that is currently being played in the Youtube's application. Is there any way I can get this using Android Player API? – cegprakash Oct 19 '16 at 22:30
  • This is the best answer I've seen for this issue. – Ram Mandal Nov 25 '16 at 05:28
  • This is working great, but how can i show thumbnail and not autoplay instead? can we – Gabriel Jun 08 '17 at 08:41
  • Your explaination so complex. If there are 2 ways, please separate for more simple to read :(( many "or", I feel nervous already hmmm... Can edit answer more effectively? – Huy Tower Jul 13 '17 at 08:45
  • this is working,but video is getting stuck while playing in fragment :( – anju jo Sep 17 '18 at 05:49
  • @anjujo please open a new question with stack trace and let me know. – Sunny Sep 17 '18 at 07:16
  • @Sunny i have already open a question.Could you please check it "https://stackoverflow.com/questions/52361191/youtube-video-get-stuck-while-playing-in-fragment" – anju jo Sep 17 '18 at 07:49
  • 1
    I used this to show my YouTubeFragment within a DialogFragment which is working. – AdamHurwitz Sep 23 '18 at 21:58
  • It's not initially clear where to place `seekToMillis()` in the YouTube lifecycle in order to handle screen rotation. I outlined how to handle this method in this [StackOverflow](https://stackoverflow.com/questions/52481759/how-to-handle-youtube-fragment-onsaveinstancestate/52481960#52481960 ) by placing it within the **PlayerStateChangeListener**. The saved instance state can be passed into the inner class that implements the state change listener to handle screen rotation properly. – AdamHurwitz Sep 24 '18 at 14:56
  • I am getting error in `transaction.add()` method saying cannot resolve method. Here is the link to error image https://imgur.com/lz6KihZ – xaif Aug 01 '20 at 03:29
  • you can see what parameters to pass in add methods. using Ctrl+P key. I don't know if add methods got changed over time. – Sunny Aug 02 '20 at 11:39
2

To implement youtube player using fragment follow these 3 steps below:-

  1. In the activity XML file add these:

     <fragment
             android:name="com.google.android.youtube.player.YouTubePlayerFragment"
             android:id="@+id/youtube_fragment"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"/>
    
  2. In activity java file create a new OnInitialize listener

    YouTubePlayer.OnInitializedListener onInitializedListener = new 
    YouTubePlayer.OnInitializedListener() {
         @Override
         public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
    
             youTubePlayer.loadVideo("Your_video_id");
    
    
    
         }
    
         @Override
         public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
    
         }
     };
    
  3. After initializing the listener get the fragment reference and initialize the player.

    YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.youtube_fragment);
    youTubePlayerFragment.initialize("You_Developer_Api_Key", onInitializedListener);
    

To get the Developer API Key follow this link.

Priyankchoudhary
  • 786
  • 9
  • 12