user6731422 user6731422 - 24 days ago 7
Java Question

redirect to main window/screen in android device on clicking the back button

I am opening a web url within my android app using this code below. My challenge is that on opening a url, it loads the page but on after navigating the url then clicking the back button of the android device instead of the app going back to the previous screen, it exits the application. This is the code

mWebView = (WebView) findViewById(R.id.webview);
mWebView.loadUrl("http://weburl.com");
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;


Please how can I make it in such a way that clicking the back button let it navigate to the previous screen of the web url.

Answer
public void onBackPressed(){

 if (mWebView.canGoBack()) {
      mWebView.goBack();
 } else {
      finish();
 }
}

I suppose this is the solution you are looking for. This would move webview to previous webpage if it has a previous page, or else it would finish the activity