android – How to refresh Youtube Player View onItemClickListener() in a ListView-ThrowExceptions

Exception or error:

I am able to play Youtube videos using cuePlaylist() but I also want to allow user to tap on any of the list item and then I want to refresh YoutubePlayerView with the video user just tapped

I am using cuePlaylist() so getting previous and next buttons as default functionality of Youtube player

So can I refresh YoutubePlayerView with the one I have selected in a ListView?

Here is my complete code, still when I do tap on any of the list item, not getting any change in YoutubePlayerView but able to Log video Id which I just clicked in a ListView

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            strVideoID = flowerList.get(i).getUrl();
            Log.d("url:", strVideoID); // getting particular video id

            youTubePlayerFragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {

                // YouTubeプレーヤーの初期化成功
                @Override
                public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
                    if (!wasRestored) {
                        player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                        player.loadVideo(strVideoID);
                        player.play();
                    }
                }

                // YouTubeプレーヤーの初期化失敗
                @Override
                public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
                    // YouTube error
                    String errorMessage = error.toString();
                    Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                    Log.d("errorMessage:", errorMessage);
                }
            });

        }
    });

    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

        if (!b) {
            youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
            youTubePlayer.cuePlaylist(PLAYLIST_ID);
        }

    }
How to solve:

You are using the wrong approach here, you don’t need to call initialize on YoutubePlayerFragment each time, the first initialization is enough which you done in onCreate method

YouTubePlayerFragment youTubePlayerFragment = YouTubePlayerFragment.newInstance();
    youTubePlayerFragment.initialize(API_KEY, this);

In the initialization listener you implemented in Activity, You should keep the reference of YoutubePlayer in a class level attribute like this

 //your class level attribute to keep reference of player
   YouTubePlayer mYoutubePlayer;

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

    if (!b) {
        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
        youTubePlayer.cuePlaylist(PLAYLIST_ID);
        //Save reference of initialized player in class level attribute
         mYoutubePlayer = youTubePlayer;
    }

}

And use this player attribute to load videos inside onItemClick instead of calling initialize again on YoutubePlayerFragment with new listener

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        strVideoID = flowerList.get(i).getUrl();
        Log.d("url:", strVideoID); // getting particular video id
        if(mYoutubePlayer!=null){
        mYoutubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
        mYoutubePlayer.loadVideo(strVideoID);
        mYoutubePlayer.play();
        }

    }
});

###

step to play any you tube video

1 create a you tube view in xml file.

<com.google.android.youtube.player.YouTubePlayerView
                android:id="@+id/youtube_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp" />
  1. inside java file

    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(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(DEVELOPER_KEY, this);
                }
            }
    
            private YouTubePlayer.Provider getYouTubePlayerProvider() {
                return (YouTubePlayerView) findViewById(R.id.youtube_view);
            }
    
        }
    

Leave a Reply

Your email address will not be published. Required fields are marked *