0

in my application I collect some data by the client. On the main layout.xml client put some data and in last they need to click on save button after that all the data will store in database or in other place. What I want when the client is in middle of the application and when he press on return button or back button then one alert box will popup that show data will loss what do you want "Yes" or "No". on clicking on "Yes" application will stop and go to the home screen and if he press on "No" button then it return to the current layout where the client entering the data.

Please give the code for this problem.

enter image description here

Vinit ...
  • 1,409
  • 10
  • 37
  • 66

1 Answers1

1

override the method onBackPressed inside your Activity to achieve this

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    CustomTabActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();

}
waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • Thanx Waqas .... I have one more problem. Please also give some Idea for this problem: http://stackoverflow.com/questions/8951236/android-return-button-not-work-when-camera-mode-is-open – Vinit ... Jan 23 '12 at 04:55