Search code examples
androidyoutubeyoutube-apiandroid-alertdialogandroid-youtube-api

Android: YouTube Video in an AlertDialog


I'm new to Android Programming! I'm wondering if it's possible to create a sort of popup view (similar to the alert dialog for example) where you can play a YouTube video! I tried but I failed!

Can you help me? I know how to play a YouTube video on a different Activity but I don't know how to do the same but in a sort of Alert Dialog!

Thanks to everyone!

M

this is my code:

b1.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View v) {
                    //Intent i = new Intent(PaginaRisultati.this, YTActivity.class);
                    final Dialog dialog = new Dialog(PaginaRisultati.this);

                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog.setContentView(R.layout.playerview_demo);
                    YouTubePlayerView youTubeView = (YouTubePlayerView) dialog.findViewById(R.id.youtube_view);
                    OnInitializedListener oil = new YouTubePlayer.OnInitializedListener() {

                        @Override
                        public void onInitializationSuccess(Provider provider, YouTubePlayer player,
                                boolean wasRestored) {
                             if (!wasRestored) {
                                  player.cueVideo("lHtJPFLgizw");
                                }

                        }

                        @Override
                        public void onInitializationFailure(Provider provider,
                                YouTubeInitializationResult errorReason) {
                            if (errorReason.isUserRecoverableError()) {
                                  errorReason.getErrorDialog(PaginaRisultati.this, RECOVERY_DIALOG_REQUEST).show();
                                } else {
                                  String errorMessage = String.format("ERROR!!", errorReason.toString());
                                  Toast.makeText(PaginaRisultati.this, errorMessage, Toast.LENGTH_LONG).show();
                                }

                        }
                    };
                    youTubeView.initialize("MY_APY_KEY", oil);

                    dialog.show();

                }

            });

XML File of dialog:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

  <com.google.android.youtube.player.YouTubePlayerView
      android:id="@+id/youtube_view"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>

</LinearLayout>

And this is the error in the LogCat:

06-11 16:57:10.225: E/AndroidRuntime(1872): FATAL EXCEPTION: main
06-11 16:57:10.225: E/AndroidRuntime(1872): Process: it.sii.android.jobaroundu, PID: 1872
06-11 16:57:10.225: E/AndroidRuntime(1872): android.view.InflateException: Binary XML file line #28: Error inflating class com.google.android.youtube.player.YouTubePlayerView
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.LayoutInflater.createView(LayoutInflater.java:620)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.app.Dialog.setContentView(Dialog.java:477)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at it.sii.android.jobaroundu.PaginaRisultati$MyExpandableListAdapter$3.onClick(PaginaRisultati.java:287)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.View.performClick(View.java:4438)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.View$PerformClick.run(View.java:18422)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.os.Handler.handleCallback(Handler.java:733)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.os.Handler.dispatchMessage(Handler.java:95)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.os.Looper.loop(Looper.java:136)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.app.ActivityThread.main(ActivityThread.java:5017)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at java.lang.reflect.Method.invokeNative(Native Method)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at java.lang.reflect.Method.invoke(Method.java:515)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at dalvik.system.NativeStart.main(Native Method)
06-11 16:57:10.225: E/AndroidRuntime(1872): Caused by: java.lang.reflect.InvocationTargetException
06-11 16:57:10.225: E/AndroidRuntime(1872):     at java.lang.reflect.Constructor.constructNative(Native Method)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at android.view.LayoutInflater.createView(LayoutInflater.java:594)
06-11 16:57:10.225: E/AndroidRuntime(1872):     ... 19 more
06-11 16:57:10.225: E/AndroidRuntime(1872): Caused by: java.lang.IllegalStateException: A YouTubePlayerView can only be created with an Activity  which extends YouTubeBaseActivity as its context.
06-11 16:57:10.225: E/AndroidRuntime(1872):     at com.google.android.youtube.player.YouTubePlayerView.<init>(Unknown Source)
06-11 16:57:10.225: E/AndroidRuntime(1872):     at com.google.android.youtube.player.YouTubePlayerView.<init>(Unknown Source)
06-11 16:57:10.225: E/AndroidRuntime(1872):     ... 22 more

Solution

  • I did it by making my activity look like a dialog. I had to resort to this solution as I had to show youtubeplayer in a fragment and nesting tag in a class extending Fragment is not allowed. Here's the code:

    public class YoutubeDialogActivity extends YouTubeBaseActivity implements
        YouTubePlayer.OnInitializedListener {
    public static final String API_KEY = "your api kery from google";
    public static  String VIDEO_ID ;
    private YouTubePlayer youTubePlayer;
    private YouTubePlayerFragment youTubePlayerFragment;
    private static final int RQS_ErrorDialog = 1;
    private MyPlayerStateChangeListener myPlayerStateChangeListener;
    private MyPlaybackEventListener myPlaybackEventListener;
    String log = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.youtube_player_dialog_activity);
        Bundle bundle = getIntent().getExtras();
        VIDEO_ID = bundle.getString("video_id");
        youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
                .findFragmentById(R.id.youtubeplayerfragment);
        youTubePlayerFragment.initialize(API_KEY, this);
        myPlayerStateChangeListener = new MyPlayerStateChangeListener();
        myPlaybackEventListener = new MyPlaybackEventListener();
    }
    
    @Override
    public void onInitializationFailure(Provider provider,
            YouTubeInitializationResult result) {
        if (result.isUserRecoverableError()) {
            result.getErrorDialog(this, RQS_ErrorDialog).show();
        }
    }
    
    @Override
    public void onInitializationSuccess(Provider provider,
            YouTubePlayer player, boolean wasRestored) {
        PlayerStyle style = PlayerStyle.MINIMAL;
        player.setPlayerStyle(style);
        youTubePlayer = player;
        youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
        youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);
        if (!wasRestored) {
            player.cueVideo(VIDEO_ID);
        }
    }
    private final class MyPlayerStateChangeListener implements
            PlayerStateChangeListener {
        @Override
        public void onAdStarted() {
        }
        @Override
        public void onError(
                com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
        }
        @Override
        public void onLoaded(String arg0) {
        }
        @Override
        public void onLoading() {
        }
        @Override
        public void onVideoEnded() {
            finish();
        }
        @Override
        public void onVideoStarted() {
        }
    }
    }
    

    Heres the theme in manifest file:

    <activity
            android:name="com.proshore.rwd.activity.YoutubeDialogActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Dialog" >
        </activity>
    

    As per the crashing the exception is preety self explanatory:

    A YouTubePlayerView can only be created with an Activity which extends YouTubeBaseActivity as its context.

    This is also one of the reason I choose to make my activity a dialog.