Fabian Montossi
Fabian Montossi

Reputation: 189

Can't close the app from a Dialog?

I have the next code, where I can't put a finish(); when I press "OK" Button(into a Dialog).

public void showAlertDialog(Context context, String title, String message,
    Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    if(status != null)
        // Setting alert dialog icon
       alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }

    });

    // Showing Alert Message
    alertDialog.show();

}   
}

What it's wrong? I mean, I don't understand so much, I am newbie, but I just don't want the solution, I want too the explanation if it's possible, please.

Upvotes: 0

Views: 159

Answers (4)

samsad
samsad

Reputation: 1241

finish() only can finish Activity.But you want to close your application then finsih() will not work. for this you have to call this method.

alertDialog.dismiss();    
System.exit(0);

Upvotes: 3

a person
a person

Reputation: 986

If you want to close an app from a dialog you can, but finish() would only finish() the current Activity? Try System.exit(0); with a listener callback to the Activity.

interface Listener{
    onOK();
}
Dialog{
    onClick(){
        Listener.onOK();
    }
}
Activity implements Listener{
    onOK(){
        this.finish();
        System.exit(0);
    }
}

Upvotes: 1

codeMagic
codeMagic

Reputation: 44571

Since you have the Context from your Activity, cast that to Activity and call finish() on it

alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        ((Activity)context).finish();
    }

Doing this you would need to make context final or make it a member variable of whichever class this is in.

Upvotes: 1

AnswerBot
AnswerBot

Reputation: 447

The possible explanation is that this function is not in your activity class. If so you will have to acquire the instance of your activity in this class . For example if it is mActivity Then use mActivity.finish() in your show function.

Upvotes: 1

Related Questions