Search code examples
androidback

Android override back button


I have a (custom) listview in Activity1. When I click on a row, Activity2 opens with another (custom) listview. In the rows of both listviews there are a couple of objects: imageview, checkbox, textview.
When I set all the checkboxes to checked in activity2, and click the BACK button of my phone, the checkbox of the respective row in the listview should be checked. However, when I click the BACK button, nothing happens (checked Logcat, no new rows, no Logs, nothing).
So I thought I override the BACK button, so when I click on it, Activity1 should open.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      Intent intentstart = new Intent(Activity2.this, Activity1.class);
      startActivity(intentstart);
      return true;
    }
    return super.onKeyDown(keyCode, event);    
 }

This works, but I have scruples. Is this a good solution? Is there a better solution? Because this murders the normal behaviour of BACK btn.

NORMAL BEHAVIOUR:

  1. Activity1 opens. I click on a row -> Activity2 opens. I click back -> I see Activity1. I click on a row -> Activity2 opens.......after playing for a couple of minutes and I am at Activity1, I click back and I am at the open screen of my app.

NEW BEHAVIOUR:

  1. Activity1 opens. I click on a row -> Activity2 opens. I click back -> I see Activity1. I click on a row -> Activity2 opens.......after playing for a couple of minutes and I am at Activity1, I click back and Activity2 opens. Then back again->Activity1 opens. Then back again->Activity2 opens and so on until I roll back all the previously opened activities.

Solution

  • Intent intentstart = new Intent(Activity2.this, Activity1.class);
    intentstart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intentstart);
    

    This flag will remove opened activity.

    For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.

    if you want to check the checkbox on activity2 and check on activity1 when go back. You should use

    startActivityForResult(intent, requestCode);//when start new activity
    
    Intent resultIntent = new Intent(); // when finish activity2
    resultIntent.putExtra("selected", selected); //send checked data to activity1
    setResult(Activity.RESULT_OK, resultIntent);
    finish();
    

    and then override onActivityResult() to check the checkbox

    P.S. You can override onBackPressed() for action when Back button is press.