Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to decide which activity we came from?

Hello Old sports !

To the point, I have 3 activity as follows :

-Activity A

-Activity B

-Activity C

in activity A I create an intent to go to activity C:

Intent intent=new Intent(getActivity(),C.class);
startActivity(intent);

in activity B I create intent to go to activity C too:

Intent intent=new Intent(getActivity(),C.class);
startActivity(intent);

in activity C I am going to do something different if it's from A and B.

The question is what is the best practice on 'how to let activity C know whether activity A or B that is calling ?

-sorry lack English, greeting from bali..

like image 793
studentknight Avatar asked Feb 22 '14 11:02

studentknight


4 Answers

You can pass a parameter with intent to another activity, in that way you can know which activity started.

Intent intent=new Intent(getActivity(),C.class);
intent.putString("activity","A");  // and same goes for B
startActivity(intent);

and in Activity C,

Intent intent = getIntent();
String previousActivity= intent.getStringExtra("activity");
like image 154
Orhan Obut Avatar answered Nov 18 '22 22:11

Orhan Obut


What you can do here is, you can pass one value say flag = "A" when it is from Activity A and flag = B when it is from Activity B via Intent and get that value in Activity C ...

In Activity A

Intent intent = new Intent(this, C.class);
intent.putExtra("flag", "A");
startActivity(intent);

In Activity B

Intent intent = new Intent(this, C.class);
intent.putExtra("flag", "B");
startActivity(intent);

In Activity C

    Intent intent = getIntent();
    String checkFlag= intent.getStringExtra("flag");

if(checkFlag.equals("A");
// It is from A

else
// It is from B
like image 33
Looking Forward Avatar answered Nov 18 '22 23:11

Looking Forward


Also you can take static variable in your both activity and then pass the value of static variable with intent.

Like ex.

public static int a = 1;

and

public static int b = 2;

and then pass this with intent

and in your last activity get the value of static variable and done. You will be able to know that from which activity you came from.

like image 2
InnocentKiller Avatar answered Nov 18 '22 21:11

InnocentKiller


You have two options.

1) Use startActivityForResult() when calling activity C. In this case you can use getCallingActivity() method to find this out.

2) Add an extra to intent when calling activity C.

// in activity A
Intent intent = new Intent(this, C.class);
intent.putExtra("calling", "A");
startActivity(intent);

// in activity B
String callingActivity = getIntent().getStringExtra("calling"); 
like image 1
sergej shafarenka Avatar answered Nov 18 '22 21:11

sergej shafarenka