Dyo Dyo - 7 months ago 18
Java Question

Sending extras to single activity from multiple activities

I have set of activities like A, B, C, D. If A is the home activity, I want to send values through put Extras to activity A from different activities.

From B:

Intent intent = new Intent(B.this, A.class);
intent.putExtra("from_B", true);
startActivity(intent)


From C:

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


From D:

Intent intent = new Intent(D.this, A.class);
intent.putExtra("from_D", true);
startActivity(intent)


In activity A:

if (getIntent().getExtras() != null) {
isCreate = (boolean) getIntent().getSerializableExtra("-----");
}


Can someone help me what should I keep in the place of (------) in activity A in order to identify from which activity it is called

Answer

In activity A, declare a String Tag :

public static final String    TAG_ACTIVITY_FROM = "WhichActivity";

In other activities, send :

Intent intent = new Intent(D.this, A.class);
intent.putExtra(A.TAG_ACTIVITY_FROM, "From_D");
startActivity(intent);

In A, get it back with :

if (getIntent().getExtras() != null) {
    String activityFrom = (String) getIntent().getStringExtra(TAG_ACTIVITY_FROM);
}

EDIT : You can put as many extras as you want, such as (from Activity D)

Intent intent = new Intent(D.this, A.class);
intent.putExtra(A.TAG_ACTIVITY_FROM, "From_D");
intent.putExtra(A.VALUE, 4);
startActivity(intent);

With in Activity A :

public static final String VALUE = "value";

if (getIntent().getExtras() != null) {
  String activityFrom = getIntent().getStringExtra(TAG_ACTIVITY_FROM);
  int value = getIntent().getIntExtra(VALUE, -1);
}