Home » Android » exception – Android: How to properly initialize YouTube Player inside activity?

exception – Android: How to properly initialize YouTube Player inside activity?

Posted by: admin May 14, 2020 Leave a comment

Questions:

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) 
How to&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.

Answer:

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

Answer:

After some digging around I found my problem. The problem was with the youtube library I was using. It was outdated and HERE all was fine 🙂

Answer:

Try with this way

Here the activity is extended from YouTubeBaseActivity which will be present in YouTubeAndroidPlayerApi.jar. This activity also contains few initialization listener methods to know the status of the youtube player. and follow this example for more help

import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.PlayerStyle;
import com.google.android.youtube.player.YouTubePlayerView;

public class MainActivity extends YouTubeBaseActivity implements
        YouTubePlayer.OnInitializedListener {

    private static final int RECOVERY_DIALOG_REQUEST = 1;

    // YouTube player view
    private YouTubePlayerView youTubeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);

        // Initializing video player with developer key
        youTubeView.initialize(Config.DEVELOPER_KEY, this);

    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider,
            YouTubeInitializationResult errorReason) {
        if (errorReason.isUserRecoverableError()) {
            errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
        } else {
            String errorMessage = String.format(
                    getString(R.string.error_player), errorReason.toString());
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        }
    }

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

            // loadVideo() will auto play video
            // Use cueVideo() method, if you don't want to play it automatically
            player.loadVideo(Config.YOUTUBE_VIDEO_CODE);

            // Hiding player controls
            player.setPlayerStyle(PlayerStyle.CHROMELESS);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOVERY_DIALOG_REQUEST) {
            // Retry initialization if user performed a recovery action
            getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
        }
    }

    private YouTubePlayer.Provider getYouTubePlayerProvider() {
        return (YouTubePlayerView) findViewById(R.id.youtube_view);
    }

}

Answer:

This is work for me

please download .Jar from here

Add YouTubeAndroidPlayerApi.jar in you bins folder.

and below activity for play Youtube video

if (url.contains(Constants.YOUTUBE_URL)) {
            final String key[] = url.split("v=");
            if (key.length > 1) {
                final Intent intent = new Intent(getActivity(), YouTubeActivity.class);
                intent.putExtra(Constants.KEY_VIDEO_KEY, key[1]);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.anim_zoom_in, R.anim.anim_zoom_out);
            } else {
                Utils.showSnackbarNonSticky(mRecyclerView, "URL is not valid", true, mContext);
            }
        }

below activity is play video

public class YouTubeActivity extends YouTubeBaseActivity 
    implements YouTubePlayer.OnInitializedListener, View.OnClickListener {

private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_youtube);
    initView();
}

//this method is for the initialization of the view component
private void initView() {
    final LinearLayout llParent = (LinearLayout) findViewById(R.id.activity_you_tube_parent_layout);
    youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    youTubeView.initialize(Constants.YOUTUBE_DEVELOPER_KEY, this);
    final TextView tvClose = (TextView) findViewById(R.id.activity_you_tube_tv_close);
    tvClose.setOnClickListener(this);

    llParent.setOnTouchListener(new OnSwipeTouchListener(this) {
        public void onSwipeTop() {
        }

        public void onSwipeRight() {
        }

        public void onSwipeLeft() {
        }

        public void onSwipeBottom() {
            finish();
            overridePendingTransition(R.anim.anim_zoom_in, R.anim.anim_zoom_out);
        }

    });

    final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    final Window window = this.getWindow();
    lp.copyFrom(window.getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp.height = WindowManager.LayoutParams.MATCH_PARENT;
    window.setAttributes(lp);
}

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        player.loadVideo(getIntent().getStringExtra(Constants.KEY_VIDEO_KEY));
        player.setShowFullscreenButton(false);
    }
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
    if (errorReason.isUserRecoverableError()) {
        errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
    }

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RECOVERY_REQUEST) {
         getYouTubePlayerProvider().initialize(Constants.YOUTUBE_DEVELOPER_KEY, this);
    }
}

protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return youTubeView;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.activity_you_tube_tv_close:
            finish();
            this.overridePendingTransition(R.anim.anim_zoom_in, R.anim.anim_zoom_out);
            break;
    }
}

@Override
public void onBackPressed() {
    final boolean backEnable = false;
    if (backEnable) {
        super.onBackPressed();
    }
}

}

XML is below

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_you_tube_parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBlackOpacity60"
android:gravity="center"
android:orientation="vertical">

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

<TextView
    android:id="@+id/activity_you_tube_tv_close"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/_100dp"
    android:padding="@dimen/_5Ddp"
    android:text="@string/close"
    android:textColor="@color/white"
    android:textSize="@dimen/_18Csp"
    app:font_name="@string/font_roboto_light" />