Understand onBackPressed method with WebView in android

1.8k views Asked by At

Please someone help me to understand. I am building a simple WebView app using android studio and have override method onBackPressed() to just make the functionality to go back if someone touches back button. Unfortunately my app closes with error "App has stopped working" meanwhile android studio also shows some run-time errors. My code is as below: - Neither this worked:

@Override
public void onBackPressed() 
{
    if (view.canGoBack())
    {
        view.goBack();
    } else
    {
        //otherwise exit my app
        super.onBackPressed();
    }
}

Nor this worked:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
    view.goBack();
    return true;
}

return super.onKeyDown(keyCode, event);
}

I don’t know what is wrong, please someone clear my point.

Update: When I run my app in emulator it works fine but when I click on back button on my device it should go back to previous page rather it stops working error in device comes out "Unfortunately, appname has stopped working" and errors messages in android studio are as following:-

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: pk.shippingexpress.shippingexpress, PID: 1996
              java.lang.NullPointerException
                  at pk.shippingexpress.shippingexpress.MainActivity.onBackPressed(MainActivity.java:42)
                  at android.app.Activity.onKeyUp(Activity.java:2193)
                  at android.view.KeyEvent.dispatch(KeyEvent.java:2664)
                  at android.app.Activity.dispatchKeyEvent(Activity.java:2423)
                  at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:547)
                  at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
                  at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:319)
                  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1962)
                  at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3852)
                  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3826)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
                  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3525)
                  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
                  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3582)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
                  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
                  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3558)
                  at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3718)
                  at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2010)
                  at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1704)
                  at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1695)
                  at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1987)
                  at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
                  at android.os.MessageQueue.nativePollOnce(Native Method)
                  at android.os.MessageQueue.next(MessageQueue.java:138)
                  at android.os.Looper.loop(Looper.java:123)
                  at android.app.ActivityThread.main(ActivityThread.java:5017)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                  at dalvik.system.NativeStart.main(Native Method) 

The complete code of my MainActivity.java is as following: -

package pk.shippingexpress.shippingexpress;

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity {

    public WebView view;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url = "http://easyonlineconverter.com";
        WebView view = (WebView) this.findViewById(R.id.express);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl(url);
        view.setWebViewClient(new WebViewClient());

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }
    @Override
public void onBackPressed() 
{
    if (view.canGoBack())
    {
        view.goBack();
    } else 

    {
        //otherwise exit my app
        super.onBackPressed();
    }
}


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}
2

There are 2 answers

3
kris larson On BEST ANSWER

First you declare a class variable:

    public WebView view;

But then you initialize a local variable that unintentionally shadows the class variable:

    WebView view = (WebView) this.findViewById(R.id.express);

So that when you get to this line

    if (view.canGoBack())

view is null.

Change other line to

    view = (WebView) this.findViewById(R.id.express);

to get the proper operation.

0
Manza On
java.lang.NullPointerException
                  at pk.shippingexpress.shippingexpress.MainActivity.onBackPressed(MainActivity.java:42)

Check once again what you have in this line. I'm using exactly the same code and works with no problems.

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