I was displaying a dialog screen with an EditText field, cancel and ok button in the MainActivity class in onCreate method as below
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("User Login");
alert.setMessage("Enter your email address");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String email = input.getText().toString().trim();
if (email == null || email.isEmpty())
{
AlertDialog.Builder alert_email = new AlertDialog.Builder(MainActivity.this);
alert_email.setTitle("Email Not Entered");
alert_email.setMessage("Please enter email.");
alert_email.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent start_mainactivity = new Intent(MainActivity.this, MainActivity.class);
startActivity(start_mainactivity);
}
});
alert_email.show();
}
else
{
doSomething();
}
}
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
System.exit(0);
}
So from the above code what i was trying to do was displaying an EditText view field to collect email from user, if user entered email, the code will continue necessary processing, but if user clicked OK
without entering data to EditText, just displaying another dialog saying that "Email not Entered"
with an OK button, here if user clicked OK
then i was starting again the MainActivity class to collect email which was working fine. The problem was
When first the main activity was started and clicked on Cancel
button the app will exit to home screen which was working as expected
When user clicked on OK
button without entering data in which main activity class was started by displaying email, cancel and ok button, now when we clicked on Cancel
button in this stage the app was unable to exit to home screen but instead opening the main activity screen again.
So how to kill the process directly when user clicked on Cancel
button at any stage
Edit
By the below suggestions i have edited the intent starting code to below and it worked
Intent start_mainactivity = new Intent(MainActivity.this, MainActivity.class);
start_mainactivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
start_mainactivity.putExtra("EXIT", true);
startActivity(start_mainactivity);