Md. Arafat Hasan
Md. Arafat Hasan

Reputation: 821

how to prevent crash during returning previous activity?

I have two activities. Main Activity and Second Activity. I have used a back button in the second activity. In the onclick event, I have used the returnHome() method to finish the second activity and return to the main activity.

    public class SecondActivity extends Activity {

    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.subscribe);

        webView = (WebView) findViewById(R.id.webView);

        webView.getSettings().setJavaScriptEnabled(true);

        webView.loadUrl("http://stackoverflow.com");




    }
    class MyWebViewClient extends WebViewClient {
          @Override

           public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
                return true;
          }
        }

    public void returnHome() {
         onBackPressed();
    }
}

But, when I pressed back button, a dialog box will appear stating the below statement with OK button.

Unfortunately, application has stopped.

How could I prevent/stop this dialog box to smoothly return to previous activity?

Upvotes: 0

Views: 536

Answers (1)

Looking Forward
Looking Forward

Reputation: 3585

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Exit?")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                MainActivity.super.onBackPressed();
            }
        }).create().show();
}

Upvotes: 1

Related Questions