1

This is an Activity of my Android App: for now I'm just testing that the going back to another activity works well. The problem is: when I hit the back button everything happens normally, but when I press the back arrow in the top left of the screen in the ActionBar, the activity doesn't enter the onBackPressed() method (and so the other activity crashes because it's expecting an intent passed). Any ideas on how to solve this?

package com.example.thefe.newsmartkedex;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

/**
 * Created by TheFe on 20/10/2016.
 */

public class MyPokeDetails extends AppCompatActivity {

    int pokeID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_poke_details);

        Intent j = getIntent();
        pokeID = j.getExtras().getInt("id");

        getActionBar();

        Button back = (Button)findViewById(R.id.back);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent (getApplicationContext(), PokemonDetails.class);
                i.putExtra("id", pokeID);
                startActivity(i);
            }
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent i = new Intent (getApplicationContext(), PokemonDetails.class);
        i.putExtra("id", pokeID);
        startActivity(i);
    }
}
Ale TheFe
  • 1,540
  • 15
  • 43
  • Read ActionBar training page. https://developer.android.com/training/appbar/up-action.html And similar question here. http://stackoverflow.com/questions/10108774/how-to-implement-the-android-actionbar-back-button – Toris Oct 21 '16 at 22:04
  • The back arrow on the `ActionBar` or `Toolbar` is the `HomeAsUp` button and is handled in `onOptionsItemSelected()`. – Abtin Gramian Oct 21 '16 at 22:07

1 Answers1

6

The back arrow on the ActionBar or Toolbar is the HomeAsUp button and is handled in onOptionsItemSelected().

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}
Abtin Gramian
  • 1,630
  • 14
  • 13
  • 1
    @AleTheFe as you can see, @Abtin Gramian used `finish();` instead of creating and starting and intent. This is the right way to "go back" :) – Saehun Sean Oh Oct 21 '16 at 22:11
  • You should also set the `android:parentActivityName` in the `AndroidManifest.xml` to prevent weird backstack issues. – Abtin Gramian Oct 21 '16 at 22:13