简体   繁体   中英

pass Data from Fragment to Fragment but bundle = null

I know that there are some similar questions but I am new to Android Studio and Java and I don't find the solution for my problem. So the thing is I know that I can pass the data from Fragment one with this code:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

And then in my second Fragment, retrieve the data using this:

Bundle bundle = this.getArguments();
if(bundle!=null)
   int myInt = bundle.getInt(key);

But my problem here is that my bundle is null and I don't get my value on the second Fragment. What I know is that my problem is probably because of Fragment fragment = new Fragment() I experimented a bit and did pass a value from my Activity and first it didn't work but then I realized that I had a line like Fragment listFragment = new Fragment() and then I used listFragment like this:

        Bundle bundle = new Bundle();
        bundle.putInt(key, value);
        listFragment.setArguments(bundle);

and then I did get my value from my Activity to my second Fragment. So I wanted to ask why this is working on my Activity and not on my Fragment.andr

Here,

Fragment fragment = new Fragment();

You are using the constructor used by the default FragmentFactory . You want to use the fragment that you have created. For example,

Fragment fragment = new FragmentTwo();

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