9

I can't for the life of me figure out how to have an activity be refreshed after pressing the back button. I currently have activity A that fires an intent to goto B and while on act B if you press back I want to go back to act A but have it refresh itself. I can use this intent to refresh the activity currently:

Intent refresh = new Intent(this, Favorites.class);
    startActivity(refresh);
    this.finish();

But I can't figure out how to properly use the onResume() function to refresh my act A after going back to it.

Mat
  • 202,337
  • 40
  • 393
  • 406
Nick
  • 9,285
  • 33
  • 104
  • 147
  • 1
    The likely reason that your current refresh scheme works is because you are running the activity in standard launchMode. This means that each invocation of startActivity(refresh) generates a new instance of activity A. Since each new instance goes through onCreate(), creating these unnecessary instances gives the appearance of refreshing your activity. To do this correctly, you really should identify the code in onCreate() that is responsible for "refreshing" the activity and move it to onResume(), as Ovidiu suggested below. – glorifiedHacker Jul 27 '11 at 20:31

3 Answers3

14

If you need a special behaviour of ActivityA when coming back from ActivityB, you should use startActivityForResult(Intent intent, int requestCode) instead of startActivity(Intent intent):

 startActivityForResult(new Intent(this, ActivityB.class), REQUEST_CODE); 

This way, you will be able to detect ActivityB's termination in ActivityA by overloading onActivityResult(int requestCode, int resultCode, Intent intent):

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == REQUEST_CODE) {
        doRefresh(); // your "refresh" code
    }
}

This works even if you terminate ActivityB by the press of the back button. The resultCode will be RESULT_CANCELLED by default in that case.

Shlublu
  • 10,917
  • 4
  • 51
  • 70
3

use startActivityForResult(intent, requestCode); to start Activity B from Activity A

then in Activity A override onActivityResult(int requestCode, int resultCode, Intent data)

there you can refresh your Activity A

Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
1

You need to place the code that updates the UI of your Activity in the onResume() method. Maybe you should post some more code or explain what exactly are you trying to update.

Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
  • I have an activity containing a listview with 5 strings retrieved from my database. Its running with a BackService method i.e if there is a change in database I will get a new notification with a string. If I click on that notification the listview should contain that string also. will OnResume() allow me to do that? – suraj May 07 '12 at 11:09