Click here to Skip to main content
15,881,172 members
Articles / Mobile Apps / Android
Tip/Trick

Handling Back Button Press in an Activity Called For Result

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
26 Jun 2015CPOL3 min read 91.6K   2   9
Understanding Android activities handling of back key press - some useful tips to avoid unexpected results or app crash

Introduction

Back key is frequently used while navigating to different screens (activities for a developer). It is important for any app developer to have some understanding of what events result out of back key press, how will these be handled by the Android OS and by their app, do they need to add specific handler methods to their code. etc.?

Background

Often beginner developers face the problems of apps crashing or other unexpected behaviour when back key is pressed from one of the activities of their app. By understanding some basic concepts, they will easily be able to get rid of these problems, and take total control over their app's behaviour (which should always be the case). The article is by no means comprehensive on this subject but helps to understand some key points.

The Code

When back key is pressed on an activity in focus, the OS or the system itself issues the finish() call for that activity, allowing the app to return to the calling activity, and ensuring the parent activity is restored in the same state in which it was before the child activity was called. So, essentially a developer does not need to do anything to handle back key presses.

But sometimes the app crashes, or the parent activity is not in the same state as it was before. The developer (being a developer) is bound to feel that he/she needs to handle the back press event to address the issue. A quick seach on browser leads him/her to developers' forums, and there are often solutions suggested to add a handling method. Two common solutions you may come across are:

  1. C#
    @override
    public void onBackPressed(){
      super.onBackPressed();
      finish();
    }
  2. C#
    @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) 
       {
            if ((keyCode == KeyEvent.KEYCODE_BACK)) 
            {
                return false; 
            }
            return super.onKeyDown(keyCode, event);
       }

Most likely you don't need any of these. The activity will be finished by itself, and parent activity will be restored. If the child activity was called with StartActivity(), you may observe no problems. It's when your activity was supposed to return some results via an intent, you may run into issues. The real issue may be in the calling activity rather than the called one. A simple understanding of what happens when back key is pressed on an activity which was called with startActivityForResult(Intent, int, Bundle) will be enough for you to know what you need to fix in your calling activity. Read on.

What you may not be expecting (at least I did not), that when back key is pressed on an activity which is supposed to return some results , the activity is finished at that point , and the control is returned to the Parent activity inside the onActivityResult() handler. So irrespective of whether the child activity finished as it was designed to, or it finished due to a back press, the control returns to onResult method in calling activity. This means you need to put the right code in this method to be able to handle the back press event.

The most common reason for app crash in such scenarios is that the intent passed to the called activity is returned null when back key is pressed, and the onActivityResult() has some code which is trying to access the data in the intent. Unless the null intent exception is handled, it has no option but to crash.

As long as you are checking the result code before using the data in the intent, you should have no problems, like below:

C#
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            
            // Do something with the data
        }
    }
}

To summarize, the key points to know, when back key is pressed on called activity are:

  1. finish() is automatically issues on called activity.
  2. Control returns to onActivityResult method of calling activity when back key is pressed on called activity.

You can handle rest past as long as you are aware of this.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAuto back button press Pin
Member 1406217620-Nov-18 23:52
Member 1406217620-Nov-18 23:52 
QuestionYou May Want to Do Something Else Pin
David A. Gray2-Jul-15 9:49
David A. Gray2-Jul-15 9:49 
AnswerRe: You May Want to Do Something Else Pin
JainGirish2-Jul-15 10:41
JainGirish2-Jul-15 10:41 
GeneralRe: You May Want to Do Something Else Pin
David A. Gray2-Jul-15 12:31
David A. Gray2-Jul-15 12:31 
QuestionQuite useful but ... Pin
Richard MacCutchan29-Jun-15 6:16
mveRichard MacCutchan29-Jun-15 6:16 
AnswerRe: Quite useful but ... Pin
JainGirish2-Jul-15 10:51
JainGirish2-Jul-15 10:51 
GeneralRe: Quite useful but ... Pin
Richard MacCutchan2-Jul-15 21:09
mveRichard MacCutchan2-Jul-15 21:09 
GeneralMy vote of 4 Pin
den2k8829-Jun-15 3:56
professionalden2k8829-Jun-15 3:56 
GeneralRe: My vote of 4 Pin
JainGirish2-Jul-15 10:57
JainGirish2-Jul-15 10:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.