Tom
Tom

Reputation: 3637

Android: Exit activity while it is created

Suppose I have code like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_msmap);
    setUpMapIfNeeded();
    if (mMap == null) {
      return;
    }

Before I start the activity I have checked google maps libraries are available. However, if there is no sim card / internet connectivity mMap still returns null.

One would think this works since the Google maps / Google play actually shows an error with "not available" with an OK button. But if one clicks it, the app hangs...

So rather, when mMap == null, I would like to simply exit the activity constructor showing an error, and then return to the prior activity. Is there any way to do that gracefully in some way?

Upvotes: 0

Views: 756

Answers (4)

Anirudha Agashe
Anirudha Agashe

Reputation: 3530

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_msmap);
    setUpMapIfNeeded();
    if (mMap == null) {
        AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
        dlgAlert.setMessage("Whatever your error is");
        dlgAlert.setTitle("Title");
        dlgAlert.setPositiveButton("Ok",
            new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            finish();
            }
        });
        dlgAlert.create().show();
    }
}

Upvotes: 1

BobTheBuilder
BobTheBuilder

Reputation: 19294

Try calling finish() when you want to exit:

  if (mMap == null) {
    finish();
  }

Upvotes: 1

blackpanther
blackpanther

Reputation: 11486

What about calling finish() within the activity, e.g.

if (mMap== null){
    finish();
}

Upvotes: 1

jaibatrik
jaibatrik

Reputation: 7533

Calling finish() would exit the Activity.

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_msmap);
  setUpMapIfNeeded();
  if (mMap == null) {
    finish();
  }
}

Upvotes: 1

Related Questions