Search code examples
javaandroidback-button

Android Back Action Button Result in App Crash


I am building a new application which composed of 3 activities namely: - Splash Screen - Activity A - Activity B, and - Activity C

From activity A user can go to both activities indicated below:

A -> B -> C (from act A user can go to B then to C). A -> C (from act A user can go straight to C). B -> C (from B user can go to C).

i also pass Serializable intent Extra between activities.

The problem that i am having is whenever i pressed the back button on the Action Bar (Top Left Corner) it always makes my app crashes (Error: NULL Pointer Exception).

I have tried to place this code on ALL of my activity.

@Override
public void onBackPressed() {
    this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
}

I tried to somehow mimic the physical backbutton behaviour since it is working when user press physical backbutton. But somewhat throws error as well.

or

public void onBackPressed(){
  super.onBackPressed();
}

or (well this one literally restart the app, which is discourage since it restart the app from splash screen).

public void onBackPressed(){
  super.onBackPressed();
  finish();
}

Does anyone know the appropriate way to implement back button?


Solution

  • The button on the top left corner is not the "Back" button, it would be the "up" button, and it's just a button in the action bar, onBackPressed refers to the hardware back button being pressed. Navigation with back and up is not necessarily the same ("back" means go to where I was before, whereas "up" means go to the upper level in the app hierarchy). Take a look at http://developer.android.com/design/patterns/navigation.html for more information.

    (Also, try to avoid a splash screen, they are highly discouraged in android design patterns)

    Edit: I forgot to mention how to actually handle the "up" button. You do that on your activity's onOptionsItemSelected:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            // Handle "up" button behavior here.
            return true;
        } else {
            // handle other items here
        }
        // return true if you handled the button click, otherwise return false.
    }