javaandroidyoutubeyoutube-api

How to stop a youtube video from playing


I've been messing with the YouTube API for Android. I've got it all set up and working. I'm using my Firebase database to send all relevant info to my app in the form of a list.

It all works great: the the list shows, the video plays from the list, and it goes into full screen OK. But if I want to click another video in my list after nothing happens. So I assume I have to stop and clear my YouTubePlayerView but I don't know how to do this.

This is how I get my strings from Firebase:

 Dl_Strings dlStrings = dataSnapshot.getValue(Dl_Strings.class);
        Downloadscount.add(" " + String.valueOf(dlStrings.downloads));
        AppNameList.add(dlStrings.name);
        urlList.add(dlStrings.url);

This is where I grab the URL and add it to my YouTube player:

mlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                urlmain = urlList.get(i).toString();
                tag = TAGGER.get(i).toString();


                App_DownLoadCounter();
                YouTubePlayerView myoutubeplayerView = (YouTubePlayerView) ((Activity)mContext).findViewById(R.id.youtube);

                YouTubePlayer.OnInitializedListener mOninitial;

                mOninitial = new YouTubePlayer.OnInitializedListener() {
                    @Override
                    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
                        youTubePlayer.loadVideo(urlmain);
                    }

                    @Override
                    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

                    }
                };

Solution

  • I think a part of code is missing from your snippet, but here's why this isn't working:

    The YouTube player needs to be initialized only once. loadVideo is not called because onInitializationSuccess is called only the 1st time you initialize the player.

    You could simply keep a reference of YouTubePlayer youTubePlayer the first time you initialize it and re use that when you need it.

    YouTubePlayer youTubePlayer;
    
    public void onCreate() {
      super.onCreate();
    
      // initialize player here and save 
      // ...
      @Override
      public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
         this.youTubePlayer = youTubePlayer;
      }
    
    }
    
    
    // in your listener
    mlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
          String videoID = urlList.get(i).toString();
          this.youTubePlayer.loadVideo(videoID);
      }
    }