Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check which the previous activity was, Android?

I can reach activity C from two different activities, A and B. Activity C has one button. I would like to check if I went to C from A or to C from B. If I went from A to C, I would like the button to do one thing and if I went from B to C, I would like the button to do another thing.

Is it possible to check which the previous activity was?

Something like this...

else if (id == R.id.action_button) {

if (previosActivity == A) {

    Intent intent = new Intent(this, NewActivity.class);
    startActivity(intent);  
}

else if (previosActivity == B) {

    Intent intent = new Intent(this, AnotherActivity.class);
    startActivity(intent);
}

return true;
}
like image 519
David Avatar asked Aug 05 '14 20:08

David


1 Answers

When you go to Activity C form any of the activities, you can pass an extra through the intent. Then you can then retrieve that extra in Activity C and use it as desired

Eg.

When you go from A to C:

Intent mIntent = new Intent(this, ActivityC.class); //'this' is Activity A
mIntent.putExtra("FROM_ACTIVITY", "A"); 
startActivity(mIntent);

When you go from B to C:

Intent mIntent = new Intent(this, ActivityC.class); //'this' is Activity B
mIntent.putExtra("FROM_ACTIVITY", "B"); 
startActivity(mIntent);

Now in Activity C, you retrieve this:

Intent mIntent = getIntent();
String previousActivity= mIntent.getStringExtra("FROM_ACTIVITY");

Then you can use

if (previousActivity.equals("A")){...}

or

if (previousActivity.equals("B")){...}

As in your question.

like image 176
rgamber Avatar answered Oct 13 '22 21:10

rgamber