Pergunta

I have the following model:

  • MainActivity navigates (through a button) to ActivityA.

  • ActivityA displays list of records as a ListView (from SQLite database).

  • If I click on any record, an intent will start ActivityB which displays the data of the selected record to be edited.

  • If I press on the device back button it will take me back to ActivityA.

  • ActivityB has a 'save' button, which if clicked will open new intent of ActivityA with the updated records (after edit), also, this button will finish() ActivityB.

  • Here if I press the device back button (after saving ActivityB and opening ActivityA), it will take me to the old ActivityA with the data before update (the older version of ActivityA), then on the second click on device back button, it will go back to MainActivity.

The question is: How can I let the device back button always go back to the hierarchical parent, instead of going to previous open activities?

OR

How can I kill the old instance of ActivityA if the user clicks on the save button in ActivityB?

Your help is appreciated.

Foi útil?

Solução 2

You can specify FLAG_ACTIVITY_CLEAR_TOP flag in the Intent used to launch ActivityA.

Intent intent = new Intent(this, ActivityA.class);
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity(intent);

If ActivityA being launched is already running in the current task, then all of the other activities on top of it will be closed including ActivityA and ActivityA is restarted with the new Intent. There will be no need to call finish() on ActivityB explicitly.

Outras dicas

In ActivityB, after the save, you should call finish() instead of opening a new instance of ActivityA. You should have ActivityA re-query and update the ListView.

Just add finish() in OnPause() of ActivityA and add this method to ActivityB.

@Overrride
  public void onBackPressed(View v) {

    Intent MainActivityIntent = new Intent(ActivityB.this, ActivityA.Class); 
    startActivity(MainActivityIntent);
    super.onBackPressed();
}

just try this, it really works...

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top