Skip to content Skip to sidebar Skip to footer

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 fin

Solution 1:

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 = newIntent(this, SecondActivity.class);
startActivityForResult(i, 1);

Passing info back from Activity 2:

@OverridepublicvoidonBackPressed() {
        IntentreturnIntent=newIntent();
        returnIntent.putExtra("hasBackPressed",true);
        setResult(Activity.RESULT_OK,returnIntent);
        finish();
    }

Receiving data in Activity 1:

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            booleanhasBackPressed= data.getBooleanExtra("hasBackPressed");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

Solution 2:

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.

Solution 3:

Override the onBackPressed() method and take the action inside this function.

@OverridepublicvoidonBackPressed() {
    // your stuff heresuper.onBackPressed();
}

Solution 4:

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.

Post a Comment for "Android, Check If Back Button Was Pressed"