0

It should work but it does not. I have an application with some activities. In example activity A and B. Order is A ->(some operation)->B->(some operation)->A... I start a new activities in this way:

//onClick method in A Activity
public void goToB(View view) {
    Intent intent = new Intent(this,BActivity.class);
    startActivity(intent);
    finish();
}

//onClick method in B Activity
public void goToA(View view) {
    Intent intent = new Intent(this,AActivity.class);
    startActivity(intent);
    finish();
}

I want to finish previous activities, so this is not solution in my case. I checked some answers here, in stackoverflow but they does not help in here.

Logcat says:

java.lang.IllegalStateException: Could not execute method of the activity
    at some places
Caused by: java.lang.reflect.InvocationTargetException
    at some places
Caused by: java.lang.IndexOutOfBoundsException
    at some places

Has anyone an idea what I am doing wrong? I think it's quite simple thing to do, but maybe I am misunderstanding finish() or startActivity() methods.

EDIT: One thing I forgot: starting a new activity works "in forward", so from A->B. From B->A it crashes.

Charliee
  • 13
  • 6

2 Answers2

1

Instead of doing it that way, try doing it this way:

public void goToA(View view) {
    Intent intent = new Intent(this, AActvity.class);
    intent.setFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

You can read about what the flag does here and here, but it'll get rid of the extra instances running once you change the activity.

However, I will mention that you must have other issues if you're getting OutOfBounds.

Community
  • 1
  • 1
Alex K
  • 8,269
  • 9
  • 39
  • 57
  • This works even worse. There are still the same errors and 'back' button now works (I do not want it to work [of course I always can override it and write an empty method]). – Charliee Jan 04 '15 at 17:03
  • @Charliee you have other issues in your code then that aren't related to the "finish" stuff. – Alex K Jan 04 '15 at 17:07
0

Assuming that can be done by Intent, better is use finish(); to return to A activity;

//onClick method in A Activity
public void goToB(View view) {
Intent intent = new Intent(this,BActivity.class);
startActivity(intent);

}

//onClick method in B Activity
public void goToA() {    
this.finish();
}

The stack you will have less space.

Iman Marashi
  • 5,593
  • 38
  • 51