Reputation: 418
i have two views and activities. On the first there is a spinner. On the second, you can create new entries (Stored in database for the spinner in activity 1). If the user is finished and pressed the back button, i have to refresh the spinner on activity 1 (because of the new entries).
Ist there a possibility to check, if the app returns to activity 1, because the back button in activity 2 was pressed?
I know, i can do it with the onResume Method, but this method is called EVERYTIME i return to activity one and not ONLY because of the back button.
I want to refresh the spinner only when the back button was pressed.
Any solution? Can i Check if the back button was pressed in the onResume method?
Upvotes: 1
Views: 15779
Reputation: 13865
You can override onBackPressed()
in the Second Activity. This will get called when the user presses the back button.
You can pass the information as a boolean hasBackPressed = true
in the setResult()
Starting Activity 2 from Activity 1:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
Passing info back from Activity 2:
@Override
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("hasBackPressed",true);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
Receiving data in Activity 1:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
boolean hasBackPressed = data.getBooleanExtra("hasBackPressed");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
Upvotes: 6
Reputation: 3815
Override the onBackPressed()
method and take the action inside this function.
@Override
public void onBackPressed() {
// your stuff here
super.onBackPressed();
}
Upvotes: 1
Reputation: 639
Use startActivityForResult()
to start the second activity, and return some value in the onBackPressed()
of the second activity. Catch that in onActivityResult()
, and refresh the spinner there.
Look into this.
Upvotes: 0
Reputation: 7772
You can start Activity 2 for result, using startActivityForResult()
. On Activity 2 you can set the result to RESULT_OK
when new items have been added. Then, in the onActivityResult()
method of Activity 1 you can check the returned result and update your data, if needed.
Upvotes: 1