Skip to content
Advertisement

How to finish an Activity inside a dialog? I called finish(); and SecondActivity.this.finish(); but they didn’t work

In the first case, finish() works properly, but it doesn’t work inside the dialog. This code is from second Activity, in the first case when I call finish() it finishes and return back to MainActivity but in the second case inside the dialog when I call finish(); the app crashes.

I can do something like

startActivity(new Intent(getBaseContext(), MainActivity.class));

inside the dialog, but I don’t want to recreate the activity. I want to call finish(); inside the dialog.

 @Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    Intent intent = new Intent();
    String content = etContentDetail.getText().toString();
    int id = getIntent().getIntExtra("id",0);
    DbHelper dbHelper = new DbHelper(this);

    switch (item.getItemId()) {

        case R.id.update:

            dbHelper.noteUpdate(id, content, DateTime.date(), DateTime.time(), System.currentTimeMillis());
            setResult(RESULT_OK, intent);
          finish()
          break;

        case R.id.delete:

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete Note");
            builder.setMessage("Are you sure you want to delete this note?");
            builder.setPositiveButton("Continue ", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dbHelper.deleteNote(id);
                    Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
            builder.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            }).create().show();

            break;
    }
        return true;
    }

Answer

Don’t directly call the methods you put inside your alert dialog button’s onClick. Move them into a single function inside DetailActivity.java instead and then call that function from the alert dialog.

In DetailActivity.java

public void deleteNote(){
   dbHelper.deleteNote(id);
   Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
   setResult(RESULT_OK, intent);
   finish();    
}

In your AlertDialog

@Override
public void onClick(DialogInterface dialogInterface, int i) {
     ((DetailActivity)requireActivity()).deleteNote()
     dismiss()                             
}
Advertisement