0

Alert Dialog disappears when the back button is clicked. Does no give me the opportunity to make a selection. This dialog is suppose to pop up when m == null || m.getPosition() == null. "m" is the variable"Marker m"

@Override
public void onBackPressed() {

    HabitEventController hec = new HabitEventController(this);

    if(m != null && m.getPosition() != null){
        hec.setHabitEventLocation(heID, m.getPosition());
   }

   if(m == null || m.getPosition() == null){
       new AlertDialog.Builder(this)
               .setTitle("Really Exit?")
               .setMessage("Are you sure you want to exit, without creating a marker?")
               .setNegativeButton(android.R.string.no, null)
               .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int whichButton) {
                       dialog.dismiss();
                       MapsActivity.super.onBackPressed();
                   }
               }).show();
   }

//Remove this call because your app will close and crash before display the dialog
   // finish();
}
pennyBoy
  • 397
  • 2
  • 17

2 Answers2

0

You have to check in this place with debug mode

 if(m == null || m.getPosition() == null)

here only the problem.

Raja
  • 2,775
  • 2
  • 19
  • 31
0

first of all You are checking wrong condition see

if(m == null || m.getPosition() == null)

1. if m is null then the second condition will throw NullPointerException as you are calling getPosition() on a null object.

  1. You are using ||(Or) in If condition with (m==null) check, which is totally wrong .

First you make it right the If statement then the following code will work in your scenario.

 new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit, without creating a marker?")
                .setNegativeButton(android.R.string.no, null)
                .setCancelable(false)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                }).show();

To check Marker in your scenario its better to create a method like this one :

   private boolean isMarkerAvailable() {
    if (m == null)
        return false;
    else if (m.getPosition() == null)
        return false;
    return true;
}

 if (!isMarkerAvailable()) {
        // Show your alert here or you can toggle 
        // the condition whatever is apropriate in your scenario
    }
ADM
  • 20,406
  • 11
  • 52
  • 83