Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to properly initialize YouTube Player inside activity?

I am trying to initiate an YouTube player inside an activity. However from time to time I keep getting this exception:

Fatal Exception: java.lang.IllegalStateException YouTubeServiceEntity not initialized

Here is how I try to initialize the youtube player in my activity. (this is done inside OnCreate() )

 try {
        final YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);

        youTubeView.initialize("KEY", new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean Boolean) {
                if(ad==null || ad.getVideo_urls() == null)
                    return;

                if (!Boolean)
                {
                    try {
                        if (ad.getVideo_urls() != null && ad.getVideo_urls().length() > 0) {
                            String url = ad.getVideo_urls().getString(0);
                            if (url.contains("youtube")) {
                                String id = ad.getVideo_urls().getString(0).split("embed/")[1];
                                youTubeView.setVisibility(View.VISIBLE);
                                MyYouTubePlayer = youTubePlayer;
                                MyYouTubePlayer.cueVideo(id);
                            }
                        } else {
                            youTubeView.setVisibility(View.GONE);
                            Log.i(Constants.getTag(), "Video not found");
                            //Making sure the MyYouTubePlayer is null and if not is being released
                            if(MyYouTubePlayer != null)
                            {
                                MyYouTubePlayer.release();
                            }
                        }
                    }
                    catch (JSONException e) {
                        youTubePlayer.release();
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
                youTubeView.removeAllViews();
            }
        });

    } catch(Exception e){
        e.printStackTrace();
        Log.e("Youtube", "error initializing youtube");
    }

The weirdest thing is that this issue is not persistent. It just happens from time to time and I have no idea why. Can you tell me what could be causing this?

Here is also the logcat:

java.lang.IllegalStateException: YouTubeServiceEntity not initialized
   at android.os.Parcel.readException(Parcel.java:1433)
   at android.os.Parcel.readException(Parcel.java:1379)
   at com.google.android.youtube.player.internal.l$a$a.a()
   at com.google.android.youtube.player.internal.o.a()
   at com.google.android.youtube.player.internal.ad.a()
   at com.google.android.youtube.player.YouTubePlayerView.a()
   at com.google.android.youtube.player.YouTubePlayerView$1.a()
   at com.google.android.youtube.player.internal.r.g()
   at com.google.android.youtube.player.internal.r$c.a()
   at com.google.android.youtube.player.internal.r$b.a()
   at com.google.android.youtube.player.internal.r$a.handleMessage()
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:4960)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
   at dalvik.system.NativeStart.main(NativeStart.java) 
like image 788
user5035668 Avatar asked Oct 05 '15 10:10

user5035668


People also ask

How do I fix an error occurred while initializing the YouTube player?

Update your Android youtube app to the latest version and it will work for Sure!! Save this answer.

What key do you need to play YouTube videos on Android?

Add API Key to play YouTube Video Add API key by visiting this link. Creates a new project or choose the existing one and create API Key and save somewhere. We will later use it in our code.


2 Answers

I am also facing this bug right now in my app. The problem happens when the user quit the Youtube player fragment containing activity without being it properly initialized. It is quite random and not easy to reproduce.

I am simply using try-catch to avoid it and luckily, it has not been reproduced yet.

try {
    mYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
} catch(IllegalStateException w){}

Again It may not be the sure solution.

One solution may be to check in OnBackPressed() whether the you-tube player has been initialized.

isInitializationComplete = false

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
    isInitializationComplete = true;
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
                                    YouTubeInitializationResult youTubeInitializationResult) {
    isInitializationComplete = true;
}
 @Override
public void onBackPressed() {
   if(!isInitializationComplete) return; 
}

Try out monkey to reproduce it more often.

adb shell monkey -p com.packagename -v 500

Here is link to issue tracker for this bug.

like image 59
Harish Rana Avatar answered Sep 30 '22 03:09

Harish Rana


I had this error as well, i worked around it by creating a custom class that extends YouTubePlayerSupportFragment , maybe my code does help you, which is working fine for me.

I initialize my youtube player like so:

private String currentVideoID = "<your video id>";
private YouTubePlayer activePlayer;

private void init() {

    initialize(ConstantsRepository.GOOGLE_API_SERVER_KEY, new YouTubePlayer.OnInitializedListener() {

        @Override
        public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
            // youtube is not installed
        }

        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
            activePlayer = player;
            activePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
            if (!wasRestored) {
                activePlayer.loadVideo(getArguments().getString("url"), 0);
            }
        }
    });
}

In your activity provide a youtube fragment in layout.xml and do the following replacement in onCreate:

 YTPlayerFragment myFragment = YTPlayerFragment.newInstance("oVkK3X9zMyI");
        getFragmentManager().beginTransaction().replace(R.id.youtube_container, myFragment).commit();

This thread is similar and helped me:

Initializing YouTube player in Fragment

This was helpful as well: Struggling with Youtube Player Support Fragment

like image 39
Falco Winkler Avatar answered Sep 30 '22 04:09

Falco Winkler