0

I've looked at multiple questions, haven't found solution yet.

I've youtube player SDK imported and a webview. One is in Live_fragment and another Article_Fragment.

This is the onBackPressed code that causes the crash:

@Override
override fun onBackPressed() {
    if (webViewE.canGoBack() || youTubePlayer.isFullScreen()) {
        youTubePlayer.exitFullScreen()
        webViewE.goBack()
    } else {
        super.onBackPressed()
    }
}

Now, webViewE.canGoBack and youTubePlayer.isFullScreen() alone works fine (if I only put in one of them), but if they're both together in the function, I get:

Attempt to invoke virtual method 'boolean android.webkit.WebView.canGoBack()' on a null object reference" and app crashes
Zain
  • 37,492
  • 7
  • 60
  • 84
NegeroKiddero
  • 41
  • 1
  • 6
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zain Jan 10 '21 at 22:01
  • what behaviour do you expect when `webViewE` is null/canGoBack returns false and `youTubePlayer.isFullScreen` returns true? Is iy possible for the webViewE to successfully run `goBacK` if `canGoBack` returns false? – Stachu Jan 10 '21 at 23:27

1 Answers1

0

This means your WebView variable is null at the time of the onBackPressed invocation. You need to make sure you properly initialise it and ensure it hasn't been nullified somehow up until possible calls to onBackPressed. If you want to axe this condition in the event that the WebView may be null, you can just add a check for null alongside your current check, i.e.:

@Override
override fun onBackPressed() {
    if ((webViewE != null && webViewE.canGoBack()) || youTubePlayer.isFullScreen()) {
        youTubePlayer.exitFullScreen()
        webViewE.goBack()
    } else {
        super.onBackPressed()
    }
}
Katapultman
  • 103
  • 2
  • 6