1

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);
                }
            });
Ale TheFe
  • 1,540
  • 15
  • 43
  • Please read the following tutorial https://developer.android.com/training/basics/intents/result.html – mhenryk Oct 21 '16 at 13:11

3 Answers3

1

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

@Override
public void onBackPressed() {
   //put Intent to go back here
 }
Pynnie
  • 136
  • 12
1

Your activity should be recreated from the last state when you go back to it. Do you check the intent you have your data in in your 2nd activity to be non null? I guess the app could crash because of that. You could also work with the savedInstanceState.

Override onSaveInstanceState and put the id you need into the bundle. If onCreate of your second Activity gets called, look if Bundle is non null and go get your value. Further info: https://developer.android.com/training/basics/activity-lifecycle/recreating.html

Florian Hansen
  • 746
  • 7
  • 19
0

You should use startActivityForResult() instead of startActivity() For details see this answer and Official documentation

Community
  • 1
  • 1
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79