Issue
Here is my MainActivity Code, while browsing in the app it has no problem, it loads almost every content of my website but pressing back button causes immediate crash of my app. Have a look at my code. And one more thing is that i can not load the horizontal progress bar. Lets say my activity_main.xml has set with android:id="@+id/progressBar2" progress bar id and now please add the java code for it in the below mentioned comment section.
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting progress horizontal progress bar
//adding admob monetization
MobileAds.initialize(this,
"ca-app-pub-8084091883486704/3115574815");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
WebView webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new clienthandle());
webView.loadUrl("https://www.google.com");
}
//should load the page within webview, skipping default web browser
public class clienthandle extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl("https://www.google.com");
return true;
}
}
//initiate navigation
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
this.webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Solution
In your onCreate, you are initializing local instance of webView. Then, in your onKeyDown, you are trying to work on top of class member WebView webView; - and I believe it was never initialized, thus NPE.
Answered By - ror
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.