Why Go Back isn't working in webview android app with this source code?

I have created a webview app for my website and I'm a beginner in Android Development. I have tried many ways but still, my code isn't working. My application has two activities with one splash screen and mainactivity when I run my app it's working fine but when I'm trying to go back suddenly the app crashes or totally exits.

package com.geroifydevelopers.geroify;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

public class SplashScreen extends AppCompatActivity {

    private WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        WebView myWebView = (WebView) findViewById(R.id.webviewID);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.loadUrl("https://geroify.com/");

    }

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






    

Upvotes: 0

Views: 236

Answers (1)

darshan
darshan

Reputation: 4579

The crash leads because your variable webView is null as you are initializing a new variable (myWebView) in your onCreate() method.

Remove WebView myWebView = (WebView) findViewById(R.id.webviewID)
& change to webView = (WebView) findViewById(R.id.webviewID)

Upvotes: 1

Related Questions