java.lang.IllegalStateException: YouTubeServiceEntity not initialized error when using YouTubePlayerApi

Once again, do NOT use fragment constructors or factory methods to work with lifecycle or context bound entities. Simply put, such entities can only be used after super.onCreate(...) has been called.

The question now is, when to call the init method?

Here’s what YouTubePlayerFragment documentation says:

The YouTubePlayer associated with this fragment will be released whenever its onDestroyView() method is called. You will therefore have to re-call initialize(String, YouTubePlayer.OnInitializedListener) whenever the activity associated with this fragment is recreated, even if the fragment instance is retained across activity re-creation by setting setRetainInstance(boolean).

You may be tempted to put init() in onActivityCreated but that’s too late, since onStart was already called and layout already performed.

Counterpart to onDestroyView is onViewCreated and that’s the perfect candidate.

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    init();
}

As suggested call setRetainInstance(true) in the fragment’s constructor. When the activity is recreated the fragment will not be recreated, only its UI will go through lifecycle events.

Leave a Comment