P Sharma
P Sharma

Reputation: 194

Alert dialog causes my android game to crash

I have created an alert dialog to exit my android game. It shows when user click back button and when someone click on YES on alert dialog game crashed.

public class MainActivity extends Activity {


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
       getActionBar().hide();
    setContentView(R.layout.activity_main); 
}

@Override
public void onBackPressed() 
{

     AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // Get the layout inflater
        LayoutInflater inflater = this.getLayoutInflater();

        //shows dialog to quit the game
        builder.setView(inflater.inflate(R.layout.dialog, null)).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {

            @Override
                public void onClick(DialogInterface dialog, int id) {
                    // TODO Auto-generated method stub
                MainActivity.this.finish();

                }
            }).setNegativeButton("No", null).show();

}}

Upvotes: 1

Views: 55

Answers (1)

Priya Singhal
Priya Singhal

Reputation: 1291

The crash may be due to bad token exception. You need to call dialog.dismiss() before activity finish ().

Also if u don't want to take any action when user clicks on "No" then you should not add it to dialog.

Upvotes: 1

Related Questions