Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing an activity on onCreate

I'm opening an Activity using this:

startActivity(new Intent(Parent.this, Child.class));

And on the child, I have this code on the onCreate function (the if contains more than just true, of course):

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (true) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("OK", null);
        builder.setTitle("Error");
        builder.setMessage("Connection error, please try later.")
            .show();
        finishActivity(0);
        return;
    }
}

Why is the activity not closing? I get the alert box, but then I have to tap the "back" button to go back.

like image 533
cambraca Avatar asked Nov 11 '10 04:11

cambraca


Video Answer


2 Answers

Try using the finish() method to close the Activity.

like image 154
Mudassir Avatar answered Oct 16 '22 20:10

Mudassir


do this in the on create

if (true) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setPositiveButton("OK", null)
           .setTitle("Error")
           .setMessage("Connection error, please try later.")
           .setCancelable(false)
           .setPositiveButton("_Yes",
                  new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int id) {
                          finish();
                  }
           })
           .show();
    return;
}

and in your AndroidManifest.xml do the following:

<activity class="MyDialogActivity" android:theme="@android:style/Theme.Dialog"/>

Now you Activity will start and show the Dialog. It feels like there is only the dialog for the user. There is an activity displayed, but it is behind the dialog. So the effect is okay. Otherwise you can create the Dialog in the activity itself (setcontentview).

like image 36
Patrick Boos Avatar answered Oct 16 '22 19:10

Patrick Boos