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.


	at android.webkit.WebViewDatabase.getCacheTotalSize(
	at android.webkit.CacheManager.trimCacheIfNeeded(
	at android.webkit.WebViewWorker.handleMessage(
	at android.os.Handler.dispatchMessage(
	at android.os.Looper.loop(

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)
		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