Send Data between fragments with FragmentTabHost

129 Views Asked by At

I want send data between fragment. the first fragment (name is FragmentTabs) contains tow tabs (fragments too) FragTab1 and FragTab2.

i want send the data between FragmentTabs and FragTab1

Here is my code:

in FragmentTabs :

    mTabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
    mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.contenttab);

    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("tab 1"),
            fragment(id).getClass(), null);

the function fragment:

private  Fragment fragment(String id){
    FragTab1 Ftab1 = new FragTab1();

    Bundle dataBndl = new Bundle();
    dataBndl.putString("id", id);

    Ftab1.setArguments(dataBndl);
    return  Ftab1 ;

}

in FragTab1:

Bundle bndl = getArguments();
getId = bndl.getString("id");

The error is caused at the last statement: getId = bndl.getString("id");

2

There are 2 best solutions below

0
Navjot.jassal On

Use Bundle to send String:

    YourNewFragment fragment = new YourNewFragment ();
    Bundle args = new Bundle();
    args.putString("YourKey", "YourValue");
    fragment.setArguments(args);
  getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();

In onCreateView of the new Fragment:

String value = getArguments().getString("YourKey");
0
lkh On

Navjot.jassal Thank you for your help

It is resolved, I need to add my databundle in the parametre of mTabHost.addTab:

mTabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.contenttab);

Bundle dataBndl = new Bundle();
dataBndl.putString("id", id);

mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("tab 1"),
        FragTab1.class, bundle);

No change in FragTab1 class