-2

I have developed an simple webview app from android stuido that will load url of page when online and show cache file when offline. But I'm getting a constant error of

 Null pointer Exception
    at java.lang.reflect.Method.invoke(Native Method)                                                                           
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit
.java:726)                                                                                 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

and Below is my Code from Mainactivity .java

package com.example.sagar.cdproutine;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Context context = null;
        WebView webView = new WebView(context);
        webView.getSettings().setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
        webView.getSettings().setAppCachePath(
            getApplicationContext().getCacheDir().getAbsolutePath());
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default

        if (!isNetworkAvailable()) { // loading offline
            webView.getSettings().setCacheMode(
                WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }

        webView.loadUrl("http://www.sagarrawal.com.np");
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager)
        getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo =
            connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
}

and from my manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sagar.cdproutine">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

I think Context is causing the problem but I don't know how to resolve it. Any Help would be largely appreciated.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

  • 2
    Possible duplicate of [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) – Selvin Jul 14 '17 at 21:30

2 Answers2

0

Am i missing something? This line right here is null and your passing it to web view.

Context context = null;

Try something like this:

WebView webView = new WebView( getApplicationContext());

  • Thanks David for quick reply , yes I did as you suggested. I removed line Context context = null; WebView webView = new WebView(context); and replaced with Am i missing something? This line right here is null and your passing it to web view. Context context = null; Try something like this: WebView webView = new WebView( getApplicationContext()); but now the app dosen't show anything only a white screen and if I replaced url "www.sagarrawal.com.np" with "www.google.com", then It opens from the phone Internet browser rather then webview itself. – Sagar Rawal Jul 15 '17 at 02:55
0

As David mentioned don't pass null Context

This is in OnCreate

webView = (WebView) findViewById(R.id.webView);
initWebView();//Initialize the WebView
webView.loadUrl(url);//pass your Url

And for initWebView();

private void initWebView() {
    webView.setWebChromeClient(new MyWebChromeClient(this));
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);        
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }
    });
    webView.clearCache(true);
    webView.clearHistory();
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setHorizontalScrollBarEnabled(false);
}

For MyWebChromeClient do this:

private class MyWebChromeClient extends WebChromeClient {
    Context context;

    public MyWebChromeClient(Context context) {
        super();
        this.context = context;
    }


}

Also look at this reference- link

Kartik Shandilya
  • 3,796
  • 5
  • 24
  • 42
  • I'm really grateful for your suggestion guys but still it is not working when i Add this in OnCreate webView.setWebViewClient(new WebViewController()); I get the error of it is an static method so couldn't be resolved . I made this app following the tutorials of stackoverflow. so I'm unaware of placement of this code. Here I have uploaded my project in Git hub , It would mean a lot to me if anyone could edit from project file and give me the code https://github.com/BlueYeti1881/CDPRoutine000 – Sagar Rawal Jul 15 '17 at 08:10
  • Thanks Novo Lucas for your Generous Effort. Before I reset my Project I was curious to where should I put second line of code starting from private void initWebView() to webView.setHorizontalScrollBarEnabled(false); }. Should I need to place if after private boolean isNetworkAvailable() { from my initial code or should I need to put it before context and as you have mentioned that webView.clearCache(true); webView.clearHistory(); in your code, But I want to cache the webpages so that user could still read even when they are offline. Am I missing here something. Please Help. – Sagar Rawal Jul 15 '17 at 08:33
  • yes you can add this method anywhere outside OnCreate. Try and see if the webVIew is loading first and you can do the caching stuff – Kartik Shandilya Jul 15 '17 at 08:55
  • I don't kow what am I doing wrong, but I entirely messed up . Here is the screenshot http://imgur.com/a/Jlndm please have a look at it – Sagar Rawal Jul 15 '17 at 09:25
  • You are making things very complex for yourself and you need to work on the basics first. Go through this thoroughly https://www.mkyong.com/android/android-webview-example/ and first of all just try to do basic implementation of WebView – Kartik Shandilya Jul 15 '17 at 12:44
  • I followed the tutorial from here, https://stackoverflow.com/questions/14670638/webview-load-website-when-online-load-local-file-when-offline, & as I use that code I got an error context was not initialized then I followed advice from david whereand then app sucessfully installed but now it was just white screen. On url if I replaced my own url with www.google.com and relaunch it then it automatically triggers mobile in app browser and opens from there but the url should have opened inside webview. I think I cleared my problem if not please let me know – Sagar Rawal Jul 15 '17 at 13:06
  • Check my answer again. The initWebView() method serves you that purpose. Also check this https://stackoverflow.com/questions/7746409/android-webview-launches-browser-when-calling-loadurl – Kartik Shandilya Jul 15 '17 at 13:16