NullPointerException in WebViewDatabase.getCacheTotalSize Fix

The following crash was cripping into the reports. There is no usage of the webview directly, but there is a usage of the webview and thus related stuff in the ads.

 

java.lang.NullPointerException
	at android.webkit.WebViewDatabase.getCacheTotalSize(WebViewDatabase.java:815)
	at android.webkit.CacheManager.trimCacheIfNeeded(CacheManager.java:548)
	at android.webkit.WebViewWorker.handleMessage(WebViewWorker.java:190)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loop(Looper.java:123)
	at android.os.HandlerThread.run(HandlerThread.java:60)


The problem is the following code:

 
	long getCacheTotalSize() {
		long size = 0;
		Cursor cursor = null;
		final String query = "SELECT SUM(contentlength) as sum FROM cache";
		try {
			cursor = mCacheDatabase.rawQuery(query, null);
			if (cursor.moveToFirst()) {
				size = cursor.getLong(0);
			}
		} catch (IllegalStateException e) {
			Log.e(LOGTAG, "getCacheTotalSize", e);
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return size;
	}

The NullPointerException that happens should in general not happen but sometimes the storage gets corrupted and then the cache database is null when it is called and it crashes.

The fix would be to check for this problem and then only use WebView and/or call the ads if there is no problem with the WebViewDatabase

 
	WebViewDatabase webViewDB = WebViewDatabase.getInstance(this);
	if (webViewDB != null) {
		// do what you wanted to do with the WebView
	}