简体   繁体   中英

Android strange behaviour with bundle

I am using a bundle to send data from an activity to a fragment.

Here is the code in the Activity:

 Bundle extras1 = new Bundle();
    extras1.putString("productId", productId);
    extras1.putString("ddsId", id1);

 frag1.setArguments(extras1);

 getSupportFragmentManager().beginTransaction().add(frame1.getId(), frag1, "fragment_grandchild1" + fragCount).commit();

Now when I run my project in debugging and I hover over exras1 I can see both productId and ddsId are the fore sure with their values.

And then ehre is my code in my fragment:

    Bundle extras = getActivity().getIntent().getExtras();
    if (extras != null) {
        productId = extras.getString("productId");
        ddsId = extras.getString("ddsId");
     }

Now the weird thing that is happening is that It is only receiving productId?

When I debug and hover over extras it only has productId and not ddsID. How could this be happening?

EDIT:

I have discovered what it is doing. For some reason, it sends my fragment the bundle that the activity class received. Not the one that I am specifying.

How can I go about changing that?

You are reading the extras from the activity. Try the following:

Bundle extras1 = new Bundle();
extras1.putString("productId", productId);
extras1.putString("ddsId", id1);

Fragment fg = new Fragment();
fg.setArguments(extras1);

Then in your fragment:

Bundle extras = getArguments();
if (extras != null) {
    productId = extras.getString("productId");
    ddsId = extras.getString("ddsId");
}

Use:

Bundle extras = getArguments();

Rather than:

Bundle extras = getActivity().getIntent().getExtras();

TIP (Hope it helps)

I have seen on many codes that if you do not have many extras it is common practices to create a static method in the fragment like this.

public static YourFragment newInstance(String extra1, int extra2) {
    Fragment fg = new YourFragment();

    Bundle args = new Bundle();
    args.putString("extra1TagId", extra1);
    args.putInt("extra2TagId", extra2);

    fg.setArguments(args);

    return fg;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM