Search code examples
androidchromecast

getting Null Pointer Exception when getting of media status in onstatusUpdated() while casting in android


I am getting NullPointerException when getting of media status in onstatusUpdated() method of RemoteMediaPlayer while casting first time. How to resolve this and i want to know about the

mRemoteMediaPlayer.requestStatus(mApiClient).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>(){});

but it works fine when casting the second time with different media while maintaining the session for same chromecast device.

mRemoteMediaPlayer.setOnStatusUpdatedListener(new RemoteMediaPlayer.OnStatusUpdatedListener() {

    @Override
    public void onStatusUpdated() {
        MediaStatus mediaStatus = mRemoteMediaPlayer.getMediaStatus();
        MediaInfo mediaInfo = mRemoteMediaPlayer.getMediaInfo();

        RemoteisPlaying = mediaStatus.getPlayerState() == MediaStatus.PLAYER_STATE_PLAYING;                                                 
    }
});

Solution

  • Just surround your code with simple null pointer checks as follows:

    mRemoteMediaPlayer.setOnStatusUpdatedListener(new RemoteMediaPlayer.OnStatusUpdatedListener() {
    
    @Override
    public void onStatusUpdated() {
        MediaStatus mediaStatus;
        MediaInfo mediaInfo;
        if(mRemoteMediaPlayer!=null){
            mediaStatus = mRemoteMediaPlayer.getMediaStatus();
            mediaInfo = mRemoteMediaPlayer.getMediaInfo();
            if(mediaStatus!=null){
                //you could even check if mediaStatus.getPlayerState() is not null here
                //before the next line of code
                RemoteisPlaying = mediaStatus.getPlayerState() == MediaStatus.PLAYER_STATE_PLAYING;         
            }
        }                                                
    }
    });