Search code examples
androidandroid-intentactivity-finish

How to send intent data back to previous activity when back arrow icon is pressed?


I have an Android app that displays elements in a GridView: each of these elements is clickable and starts an Activity with its details; then you can go through another activity from the second one to add more data. My question is: when I go back from 3rd to 2nd activity, my app crashes (and I know this is because going from 3rd activity to 2nd one, the 2nd so called hasn't got the intent data that it needs).

What can I do to solve this issue? My Gridview calling the 2nd activity

gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Intent i = new Intent(getApplicationContext(), PokemonDetails.class);
                i.putExtra("id", position);
                startActivity(i);
            }
        });

My 2nd activity calling the 3rd:

pokeDetails.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(getApplicationContext(), MyPokeDetails.class);
                    startActivity(i);
                }
            });

Solution

  • you can just override the onBackPressed() method with the same function of your buttons.

    @Override
    public void onBackPressed() {
       //put Intent to go back here
     }