Charliee
Charliee

Reputation: 13

Changing activities with intent does not work

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.

Upvotes: 0

Views: 621

Answers (2)

Iman Marashi
Iman Marashi

Reputation: 5753

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.

Upvotes: 0

Alex K
Alex K

Reputation: 8338

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.

Upvotes: 1

Related Questions