I don't know how to phrase this question.
My app has a simple ViewPager and you click on something in one of those page Fragments and it takes you to another Activity. Press the back button and it takes you back to the ViewPager. Press back again and it closes the app.
However, sometimes when I press the back key at the ViewPager, it takes me back to the other Activity again, and then I press back and it takes me to the ViewPager, and so on, until the app finally closes. In other words it's like there are spare, leftover instances of either the ViewPager or the other Activity in the backstack (I think it's called), but I have no idea how or why this is happening.
I also don't know how to reproduce the error, which is even more frustrating. Most of the time it works as expected, but sometimes the leftover instances just show up out of nowhere as I am pressing back.
How can I guarantee better that when I press the back button on the other Activity, it goes back to the ViewPager, and when I press back on the ViewPager, it closes the app?
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: //called when I press back button on the phone or the back-arrow on the toolbar
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//and then usually that's all I have, but in one particular Activity, I do override the function:
@Override
public void onBackPressed() {
if (some conditions are met) {
finish();
super.onBackPressed();
}
else {
//display some error message
}
}
Here is how I launch my Activities:
public void launchSomeActivity() {
Intent intent = new Intent(getActivity(), ActivityName.class);
intent.putExtra( etc etc etc );
startActivityForResult(intent, REQUEST_CODE);
}