I'm currently trying to make a WebView based app.
This is the code I currently have:
WebView webview = new WebView(this);
setContentView(webview);
WebView webView = (WebView) findViewById(R.id.myWebView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webView.setWebViewClient(new NewWebViewClient());
webview.loadUrl("http://google.com");
And the "NewWebViewClient" class is under this also in the MainActivity.java
public class NewWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
There is no error shown by Android Studio. But if I want to start the app on my smartphone it just crashes.
The same Problem I have with this:
public void onKeyDown() {
WebView webView = (WebView) findViewById(R.id.myWebView);
if (webView.copyBackForwardList().getCurrentIndex() > 0) {
webView.goBack();
}
else {
super.onBackPressed();
}
}
Does anyone know how I get this both things get working?
EDIT:
It still crashes:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebViewClient(android.webkit.WebViewClient)' on a null object reference
Try this
@Override
public void onBackPressed() {
WebView webView = (WebView) findViewById(R.id.myWebView);
if(webView!=null)
{
if(webView.canGoBack())
{
webView.goBack();
}
else
{
super.onBackPressed();
}
}
}
After reading ur question, i think u need to perform go back when the user press the back button... If thatz whats u luking for u can use the above code...
And replace
WebView webview = new WebView(this);
with
WebView webView = (WebView) findViewById(R.id.myWebView);