Arihant Arihant - 10 months ago 74
Android Question

Back button for previous page on android webview not working

I am trying to override the back button so that it goes back the previous page but it just exits the application. Here;s the code.. please tell me where am i going wrong.

package com.example.thebase;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainAccelerometer extends Activity implements AccelerometerListener{

WebView myWebView;
//Back Button Code
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(myWebView.canGoBack() == true){
myWebView.goBack();
}else{
finish();
}
return true;
}

}
return super.onKeyDown(keyCode, event);
}


//--------------------


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accelerometer_example_main);
//ENABLING JAVASCRIPT CODE
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);


//WEBVIEW CODE
myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.pingcampus.com/greedy/get_category.php");


//WebView client
myWebView.setWebViewClient(new HelloWebViewClient());

//Back Button

//------


};
//rest of the code

TNR TNR
Answer Source

You have onBackPressed() method to override instead of onKeyDown(). Replace onKeyDown() with onBackPressed() as below:

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

}

EDIT

Also check 3rd line in your onCreate()

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

You are declaring myWebView as local variable again and global variable is not instantiated which is throwing NullPointerException and crashes the app.

So change the your 3rd line of code as below:

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