0

The app places WebView on screen with some preloaded content. There is data download running in background. When this data is ready, the WebView is being setup. The problem occurs if the user switches to other activity while data download is in progress:

void onDataLoaded() {
    WebView wv = getWebView();
    if (wv != null) {
        wv.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.Black));

And the exception is:

java.lang.NullPointerException
    at android.webkit.WebViewClassic.setBackgroundColor(WebViewClassic.java:8852)
    at android.webkit.WebView.setBackgroundColor(WebView.java:2210)
    at com.sample.app.TestActivity.onDataLoaded(TestActivity:45)

How can I prevent this crash if the WebView has been removed from the screen?

UrK
  • 2,191
  • 2
  • 26
  • 42
  • 2
    do `wv.setBackgroundColor( getApplicationContext().getResources().getColor(R.color.Black));` – M D Oct 18 '15 at 10:46
  • 1
    Context.getResources().getColor(int) has been deprecated. Recommended replacement is _ContextCompat_. – UrK Oct 18 '15 at 11:00
  • 1
    how did you know?? and where is _Google_ documented it? – M D Oct 18 '15 at 11:02
  • *WebView has been removed from the screen* what do you mean by *removed from the screen*? – Blackbelt Oct 18 '15 at 11:08
  • Sorry. You are correct. Google recommends using _getColor(int, Theme)_: http://developer.android.com/reference/android/content/res/Resources.html#getColor(int, android.content.res.Resources.Theme). The support for this call though comes in SDK 23+ which is not my case. I am targeting 17+. This still does should prevent the crash, as the crash happens in _WebView.setBackgroundColor()_ which receives non-null _int_ as a parameter. – UrK Oct 18 '15 at 11:13

0 Answers0