Brigante
Brigante

Reputation: 1981

Android enable back button in webview

I'm using the following code to display a webview in my Android app.

package com.company.myapp;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class ArticlesActivity extends Activity {

    /** Initialize the Google Analytics Tracker */
    GoogleAnalyticsTracker tracker;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
        WebView webview = new WebView(this);
        setContentView(webview); 
        setProgressBarVisibility(true); 
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        final Activity activity = this;
        tracker = GoogleAnalyticsTracker.getInstance();
        // Start the tracker, updating google every 20 seconds
        tracker.start((String) getText(R.string.analyticsID), 20, this);

        webview.setWebChromeClient(new WebChromeClient() { 
          public void onProgressChanged(WebView view, int progress) { 
            activity.setProgress(progress * 100 ); 
          } 
        }); 

        webview.setWebViewClient(new WebViewClient() { 
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
            }
        });
        webview.loadUrl("http://www.google.com");
    }
    @Override
    public void onResume() {
        tracker.trackPageView("ArticlesActivity");
        super.onResume();
    }
    @Override
    protected void onDestroy() {
      super.onDestroy();
      // Stop the tracker when it is no longer needed.
      tracker.stop();
    }
}

I would need to enable the back button to step back if history exists instead of just exiting the webview.

I've tried many different code examples such as this but can't get any to work. The app just shuts down when the back button is pressed.

Here's my code with the back button code but it just crashes the app when then back button is pressed:

package com.company.myapp;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class ArticlesActivity extends Activity {

    WebView webview;

    /** Initialize the Google Analytics Tracker */
    GoogleAnalyticsTracker tracker;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
        WebView webview = new WebView(this);
        setContentView(webview); 
        setProgressBarVisibility(true); 
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        final Activity activity = this;
        tracker = GoogleAnalyticsTracker.getInstance();
        // Start the tracker, updating google every 20 seconds
        tracker.start((String) getText(R.string.analyticsID), 20, this);

        webview.setWebChromeClient(new WebChromeClient() { 
          public void onProgressChanged(WebView view, int progress) { 
            activity.setProgress(progress * 100 ); 
          } 
        }); 

        webview.setWebViewClient(new WebViewClient() { 
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
            }
        });
        webview.loadUrl("http://www.google.com");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            webview.goBack();

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

    @Override
    public void onResume() {
        tracker.trackPageView("ArticlesActivity");
        super.onResume();
    }
    @Override
    protected void onDestroy() {
      super.onDestroy();
      // Stop the tracker when it is no longer needed.
      tracker.stop();
    }
}

Could someone help me with a solution?

Upvotes: 3

Views: 7745

Answers (1)

Rahul Choudhary
Rahul Choudhary

Reputation: 3809

Got it! Your problem in this line

WebView webview = new WebView(this);

Instead of using your member variable you are creating a variable inside function, and hence your member variable is null inside onKeyDown function.

Just replace it with

webview = new WebView(this);

Upvotes: 7

Related Questions