Search code examples
javaandroidbutterknife

How to access YouTubePlayerView inside Butterknife onlick function


Using this method is throwing a null object reference. Butterknife wont allow any refrence to view inside the void go(){ function. Is there a way to access this view YouTubePlayerView youTubePlayerView = player_view; inside the function?

.java

 @BindView(R.id.youtube_player_view) YouTubePlayerView player_view;

   YouTubePlayerView youTubePlayerView =  player_view;
    //start view trailer
    @OnClick(R.id.iv_play_circle)
    void go(){

       String vid = video.getVideoKey(); 

       if(vid != null){

           youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
               @Override
               public void onReady(@NonNull YouTubePlayer youTubePlayer) {
                   youTubePlayer.loadVideo(vid, 0);
               }
           });

        }
    }//end view trailer


    @Override
    public void onDestroyView () {

        if(youTubePlayerView != null) {
            youTubePlayerView.release();
        }
        super.onDestroyView ();
  
    }

error log

E/CustomActivityOnCrash: The previous app process crashed. This is the stack trace of the crash:
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView.addYouTubePlayerListener(com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.YouTubePlayerListener)' on a null object reference
       

Solution

  • @BindView(R.id.youtube_player_view) YouTubePlayerView player_view;
    YouTubePlayerView youTubePlayerView =  player_view;
    

    Here you're expcting the value of youTubePlayerView to be the same as the 'filled' value of the player_view view variable, but in reality, this assigment is done at the time before the player_view has been bound to the view.

    That is because the @BindView takes effect after ButterKnife.bind(this) is called on your onCreate(), but your assignment is done on the class initialization.

    Either just use player_view directly, or do the youTubePlayerView = player_view; after you have called ButterKnife.bind(this).