I am building a simple android app. I have a webview that loads an url. When I press the back button, the app returns back to the previous page or if it is already there, an alert dialog shows that asks whether you want to leave the app or not. I also have a custom template to use when there's no internet connection. Everything is working fine but when I don't have any connection, when I press the back button, the alert dialog doesn't pop. This is my problem. I know that pressing the home button will exit the application but I want to be able to do so by pressing the back button.
public class MainActivity extends AppCompatActivity {
private WebView webView;
SwipeRefreshLayout swipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webView = findViewById(R.id.WebView1);
String url = "myCustomLink";
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new MyBroswer());
webView.loadUrl(url);
swipe.setRefreshing(true);
}
private class MyBroswer extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUri){
webView.loadUrl("file:///android_asset/error.html");
}
public void onPageFinished(WebView view, String url){
swipe.setRefreshing(false);
}
}
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
}
else{
new AlertDialog.Builder(this)
.setTitle("Leave app?")
.setMessage("U sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
Its not working because you declared both onBack and Dialog inside of the MyBrowser class. When you don't have internet connection, your class is simply not executed. Declare your onBack outside of MyBrowser so that its not dependent on your internet connection