YingYang YingYang -3 years ago 172
Android Question

Android, check if back Button was pressed

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?

Answer Source

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:

    public void onBackPressed() {
        Intent returnIntent = new Intent();

Receiving data in Activity 1:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            boolean hasBackPressed =data.getStringExtra("hasBackPressed");
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download