Gabriel Thá
Gabriel Thá

Reputation: 1

How can I solve WebViewClient breaking application?

I am trying to add a WebViewClient to my WebView application. But every time I try to start it with WebViewClient, it stops working.

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        MyWebViewClient webViewClient = new MyWebViewClient(this);
        myWebView.setWebViewClient(webViewClient);

        myWebView = findViewById(R.id.webview);
        myWebView.loadUrl("https://www.google.com.br/");

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

MyWebViewClient.java

public class MyWebViewClient extends WebViewClient {

    private Activity activity = null;
    public MyWebViewClient(Activity activity) {
        this.activity = activity;
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        if(url.contains("https://google.com/")) return false;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        return true;
    }

}

When I comment the line myWebView.setWebViewClient(webViewClient); in the MainActivity.java the application works again. Any ideas on how to solve this WebVIewClient problem?

Upvotes: -2

Views: 94

Answers (1)

vikas kumar
vikas kumar

Reputation: 11028

Here you go, you are setting the client on myWebView before its initialization.

    public class MainActivity extends AppCompatActivity {

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

        //should be initialized first
        myWebView = findViewById(R.id.webview);

        MyWebViewClient webViewClient = new MyWebViewClient(this);
        myWebView.setWebViewClient(webViewClient);


        myWebView.loadUrl("https://www.google.com.br/");

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

Upvotes: 0

Related Questions