Question

I have a simple webview to shows a forum..i need "mapping" the back button to go back in the webpages of the forum of course. I tryied in This way but gets me a fatal error

public class MainActivity extends Activity
{
protected WebView webview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    WebView webview = (WebView) findViewById(R.id.webview);
    WebSettings websettings = webview.getSettings();
    websettings.setJavaScriptEnabled(true);
    webview.setWebViewClient(new WebViewClient());
    if (savedInstanceState == null)
    {
        webview.loadUrl("http://www.proboards.com/");
    }

}

@Override
protected void onSavedInstanceState(Bundle outState) {
    //super.onSavedInstanceState(outState);

    webview.saveState(outState);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if(webview.canGoBack() == true)

                webview.goBack();
            else finish();
            break;

        default:
            break;
    }
    return super.onKeyDown(keyCode, event);
}
}

The error is onKeyDown line 42.

Was it helpful?

Solution

Change this

 WebView webview = (WebView) findViewById(R.id.webview); 
 // webview becomes local

To

 webview = (WebView) findViewById(R.id.webview); 

You have already declared

 WebView webview;

as a class member

OTHER TIPS

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if(webview.canGoBack() == true)

                webview.goBack();
            else finish();
            return true;
    }
    return super.onKeyDown(keyCode, event);
}

this is the duplicate of: How to go back to previous page if back button is pressed in WebView?

in any case you have to return true if you handled the key down action

Try this way

Do not override onKeyDown() method

@Override
    public void onBackPressed() {
        if(webview.canGoBack()){
            webview.goBack();
        }else{
            super.onBackPressed();
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top