Reputation: 104
Let say I have 3 Activities, Activity A
, Activity B
and Activity C
.
Activity A and Activity B sends an intent to activity C with let say the following code:
ActivityA sending an intent:
Intent i = new Intent();
i.putExtra("ListName", s);
i.setClass(ActivityA.this, ActivityC.class);
startActivity(i);
ActivityB sending an Intent:
Intent i = new Intent();
i.putExtra("PersonName", s);
i.setClass(Activityb.this, ActivityC.class);
startActivity(i);
How do I know in ActivityC which Intent has been received, because whenever ActivityC is called it will always pass this line of code, either for ActivityA or ActivityB
if(getIntent() != null && getIntent().getExtras() != null)
and then give me NullPointerException
on this line of code, if the intent was sent from ActivityB
String s = getIntent().getStringExtra("ListName");
Upvotes: 3
Views: 2652
Reputation: 82
You need to add one extra value to the intent with the classs name of the calling activity
Intent intent = new Intent();
intent.setClass(A.this,MyActivity.class);
intent.putExtra("ClassName","A");
A.this.startActivity(intent);
Intent intent = new Intent();
intent.setClass(B.this,MyActivity.class);
intent.putExtra("ClassName","B");
B.this.startActivity(intent);
Intent intent = new Intent();
intent.setClass(C.this,MyActivity.class);
intent.putExtra("ClassName","C");
C.this.startActivity(intent);
And then in MyActivity's onCreate Method
Intent intent = this.getIntent();
if(intent !=null)
{
String clsname= intent.getExtras().getString("ClassName");
if(clsname.equals("A"))
{
//Do Something here...
}
if(clsname.equals("B"))
{
//Do Something here...
}
if(clsname.equals("C"))
{
//Do Something here...
} }
}
else
{
//do something here
}
Upvotes: 0
Reputation: 3212
Add an extra field for class name in Intent,
In ActivityA,
Intent i = new Intent();
i.putExtra("ListName", s);
i.putExtra("Class","A");
i.setClass(ActivityA.this, ActivityC.class);
startActivity(i);
In ActivityB,
Intent i = new Intent();
i.putExtra("PersonName", s);
i.putExtra("Class","B");
i.setClass(Activityb.this, ActivityC.class);
startActivity(i);
In your ActivityC, check the tag "Class"
String className = getIntent().getStringExtra("Class");
if(className.equals("B"))
{
String s = getIntent().getStringExtra("ListName");
}
Upvotes: 4
Reputation: 24998
So here is what's happening:
Say activity C was started by activity B. Would there be a string associated with the key named ListName
? No. Hence the null value.
So how do you differentiate between the activities?
One way is to put a field in the intent extras which tell you which activity it is.
The other way is this:
String s = getIntent().getStringExtra("ListName");
if( s != null ){
// do what you would do if activity B started activity C
}
Upvotes: 1
Reputation: 3763
Add one more extra with your Intent;
Intent i = new Intent();
i.putExtra("TAG",classname);
i.putExtra("key","value");
Upvotes: 3