Ashonko
Ashonko

Reputation: 623

Go back to previous page with back button not working

Pardon me, if this question had been asked too many times before. But I have been trying to solve it for a while and tried all the solutions but nothing seems to work for me. Can you please point me what I'm missing here? When I press the back button on the mobile, it exits the app instead of going to the back page of the webView. I'll really appreciate your help on what I'm doing wrong here.

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends Activity {
    private WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.webView1);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("file:///android_asset/index.html");

    }
    @Override
    public void onBackPressed() {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

Upvotes: 0

Views: 247

Answers (2)

cybersam
cybersam

Reputation: 67044

This statement in onCreate defines a local variable named myWebView that hides the instance variable with the same name:

WebView myWebView = (WebView) findViewById(R.id.webView1);

So, the instance variable will have a null value and onBackPressed is likely throwing a NullPointerException.

Try changing that statement to this:

myWebView = (WebView) findViewById(R.id.webView1);

Upvotes: 2

Xay
Xay

Reputation: 248

Try this

mainView.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
            if ((keyCode == android.view.KeyEvent.KEYCODE_BACK)) {
                if(webView!=null)
                {
                  if(webView.canGoBack())
                  {
                    webView.goBack();
                  }
                }
            }
        }
        return true;
    }
});

Upvotes: 0

Related Questions