Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert Dialog negative button to same activity

I am trying a simple app, where user enters his number. And I show an alert dialog to confirm his mobile number. If user chooses "YES" I am redirecting him to next activity. But the problem is, if user select "NO" I want to show the same activity for editing the number.

Now I am doing this by calling an Intent of the same activity. But it is a bad practice. How can I show the same activity with last entered number in the activity?

Here is how I tried. on button press

phoneNum = (EditText) findViewById(R.id.editTextPhoneNumber);
String phNum = phoneNum.getText().toString();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
        MainActivity.this);
alertDialog.setTitle("CONFIRM");
alertDialog.setMessage("Is this your correct number? \n" + phNum
        + " a SMS will be sent to verify your phone number.");
alertDialog.setPositiveButton("YES",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                sendOtp();
                Intent myIntent = new Intent(getApplicationContext(),
                        Activity2Activity.class);
                startActivity(myIntent);
            }
        });
alertDialog.setNegativeButton("NO",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // dialogInterface.cancel();
                Intent sameIntent = new Intent(MainActivity.this,
                        MainActivity.class);
                startActivity(sameIntent);
                finish();
            }
        });
alertDialog.show();
like image 806
Aparichith Avatar asked Aug 11 '26 04:08

Aparichith


2 Answers

You can read this reference document: Official Doc : Dialog Dismiss

Notice this sentence: When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for you.
No matter the user click which button that generated by Builder, the system dismisses the dialog.

alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //Just leave it empty here.
    }
});
like image 83
林佳蓉 Avatar answered Aug 14 '26 22:08

林佳蓉


As you just need to display the same activity, just dismiss the dialog box while you click the negative button.

alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    @Override 
    public void onClick(DialogInterface dialogInterface, int i) {
        alertDialog.dismiss();   
    }
}
like image 33
Shaik MD Ashiq Avatar answered Aug 14 '26 22:08

Shaik MD Ashiq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!