How do I navigate to the parent activity that needs to be launched with additional data data?

Suppose I have an application that Activity A

will display a message as well as its comments. If I click one of the comments it goes to Activity B

. So Activity B

will show the comment and also respond to that comment. So far, I have no problem. I just need to set parent Activity

for Activity B

in Activity A

in manifest.xml

.

Now I also have Activity X

one that will show the user's profile as well as all their posts and comments. If I click on a comment, it goes to Activity B

. But, if I press the button, it goes back to Activity X

. How do I get it back to Activity A

?

By the way, to get started Activity A

, I need to provide additional data containing the ID for this post and for each comment, they also have their own post ID ID.

Can you do the following in Activity B

?

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // if come from Activity A:
                NavUtils.navigateUpFromSameTask(this);
            // else
                Intent intent = new Intent(this, ActivityA.class);
                intent.putLong("ID", comment.getPostId());
                startActivity(intent);
            return true;
        default:
    }

    return super.onOptionsItemSelected(item);
}

      

Or do I need to use something like TaskStackBuilder

to run Activity B

from Activity X

?

+3


source to share


1 answer


There are different approaches to this. My favorite is passing the necessary information to Intent

something like this when setting up

  Intent intent = new Intent();
  String caller = getIntent().getStringExtra(CALLER_ACTIVITY);
  if (caller.equals(ActivityA.class.getName())) {
      NavUtils.navigateUpFromSameTask(this);
      return; // dont need to do anything
  } else if (caller.equals(ActivityX.class.getName())) {
      intent.setClass(this, ActivityA.class);
  }
  intent.putExtras(getIntent().getExtras()); // if more info needed
  startActivity(intent);
  finish();

      

Another approach would be to use getCallingActivity

, but this only works when starting the Activity with startActivityForResult()

.
If you are using AppCompat

you can get the caller using AppCompat.getReferrer ()



The behavior can change the above parameters, so it is recommended to use the Intent method.

You can run ActivityB

like this,

Intent intent = new Intent(this, ActivityB.class);
intent.putExtra(ActivityB.CALLER_ACTIVITY, this.getClass().getName());
startActivity(intent);

      

+1


source







All Articles