Search code examples
androidwebviewback-buttonback

Android Webview back button event


Why doesnt this code work ?

i searched on stackoverflow, tried several codes and they all dont work.

[MainActivity.java]

package com.example.jquery;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
    WebView webView;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        WebView webView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("file:///android_asset/www/framework/lib/homescreen.html");

        return;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        else
        {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

When i press the backbutton the app crashes.


Solution

  • You need to change your webView variable to initialize the class variable instead of recreating the Webview variable inside of onCreate().

    Change this line:

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

    To this:

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