title: Exit App Confirmation Dialog Appearing Multiple Times
body: <p>I have an application with two pages mainly main and second.</p>
  
  <p>I am traversing from main to second and vice-a-verse.</p>
  
  <p><code>MainActivity.java</code> has following code:</p>
  
  <pre><code>Button btnSecond = (Button) findViewById(R.id.btnSecond);
  
      btnSecond .setOnClickListener(new View.OnClickListener() {
  
          @Override
          public void onClick(View v) {
              // TODO Auto-generated method stub
              Intent j = new Intent(MainActivity.this,Second.class);
              startActivity(j);
          }
      });
  </code></pre>
  
  <p><code>Second.java</code> has following code:</p>
  
  <pre><code>Button btnClose = (Button) findViewById(R.id.btnClose);
  
          btnClose .setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  // TODO Auto-generated method stub
                  Intent j = new Intent(Second.this,MainActivity.class);
                  startActivity(j);
              }
          });
  </code></pre>
  
  <p>I have added the app exit confirmation dialog function in <code>MainActivity.java</code></p>
  
  <pre><code>@Override
      public void onBackPressed() {
          new AlertDialog.Builder(this)
          .setMessage("Are you sure you want to exit?")
          .setCancelable(false)
          .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                  MainActivity.this.finish();
              }
          })
          .setNegativeButton("No", null)
          .show();
      }
  </code></pre>
  
  <p>The problem is that when i come from second page to main page and then press the back button on the device i get the alert two times.</p>
  
  <p>As far as my understanding is concerned this happens because the MainActivity was loaded twice in the background : one when i clicked on the second button on the main page and traversed to the second screen and second when i clicked on the close button on the second page and traversed to the main page.</p>
  
  <p>What i want is that the there should be a single confirmation dialog and clicking on yes should close the main activity even if it is loaded multiple times.</p>