-3

Currently I have an application that has the following code. If the user doesnt save the project before clicking the back button, I provide a dialog box to see if they want to save it prior to exiting the activity.

  case android.R.id.home:
      if(!didWeSave){
          SHOW THE DIALOG BOX WITH OPTIONS
      } else {
         NavUtils.navigateUpFromSameTask(this);
      }
   return true;

Right now, it only works properly when the user hits on the back arrow from within the application. However, it does not work when I hit the back button on the physical device. How would this be fixed?

Thanks

Naveen Kumar M
  • 7,497
  • 7
  • 60
  • 74
  • 1
    [Are you overriding onBackPressed()?](http://stackoverflow.com/questions/18337536/android-overriding-onbackpressed/18337567#18337567) – codeMagic Sep 14 '15 at 13:45

3 Answers3

1

Try Overriding the onBackPressed() of your activity, and showing the dialog there.

Mateus Brandao
  • 900
  • 5
  • 9
1

just add

@Override
public void onBackPressed() {
    //SHOW THE DIALOG BOX WITH OPTIONS
}

in your activity

Fakher
  • 2,098
  • 3
  • 29
  • 45
0

The above answers are right, but for completion, You have to comment out super(), to avoid activity is closing without user interaction on Your dialog and provide window leaks.

public void onBackPressed() {

 //do Your stuff here
   showDialog();

 //comment out super() here
 //super.onBackPressed();

}
Opiatefuchs
  • 9,800
  • 2
  • 36
  • 49