Steven Carlborg
Steven Carlborg

Reputation: 185

Detect that an activity has closed in Android

In my application I need to launch a SelectionActivity to select one of the options. Once the option has been selected I need to refresh another list on the MainActivity.

This is the code that I use to launch the SelectionActivity:

Intent intent = new Intent(MainActivity.this, SelectionActivity.class);
startActivity(intent);

In SelectionActivity this is the code that receives the selected option an closes the activity:

selectedValue = adapter.getItem(position);
finish();

Now the application comes back to MainActivity but I don't know how to receive an event that the SelectionActivity has closed.

Thanks

Upvotes: 11

Views: 12632

Answers (7)

ekashking
ekashking

Reputation: 447

Use onDestroy:

public void onDestroy() {
    super.onDestroy();

    Log.w("test", "active");
}

Upvotes: -1

noelicus
noelicus

Reputation: 15055

Quick snippet showing use of startActivityForResult:

private static final int MY_REQUEST_CODE = 0xe110; // Or whatever number you want
// ensure it's unique compared to other activity request codes you use

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

    if (requestCode == MY_REQUEST_CODE)
        ActiviyFinishedNowDoSomethingAmazing();
}

public void onClickStartMyActivity(View view)
{
    startActivityForResult(new Intent(this, GameActivity.class), MY_REQUEST_CODE);
}

More reading on getting a result from an activity.

Upvotes: 13

iTurki
iTurki

Reputation: 16398

Solution 1 :

  1. Make selectedValue a static public variable.
  2. In your MainActivity :

    void onResume() {
            result = SelectionActivity.selectedValue;
    }
    

Solution 2 :

If the SelectionActivity's job is simply a selection from multiple options, Consider using Dialogs

Upvotes: 1

Jon Willis
Jon Willis

Reputation: 7024

Look into startActivityForResult()

Upvotes: 0

Dan S
Dan S

Reputation: 9189

Depending on your application's design you can refresh the list each time the Main activity is returned to by watching the onResume() or onRestart() events. In addition there is startActivityForResult(). All of these methods are in Activity.

Upvotes: 1

b_yng
b_yng

Reputation: 14136

Use onActivityResult() or make selectedValue static. In MainActivity use the onResume method:

protected void onResume() {
    if(SelectionActivity.selectedValue != 0)
          newValue = SelectionActivity.selectedValue;
}

Upvotes: 0

Daniel Werner
Daniel Werner

Reputation: 128

startActivityForResult(), then override the onActivityResult() method. There are a lot of examples one can google for just using the key word startactivityforresult.

Upvotes: 0

Related Questions