Search code examples
androidandroid-fragmentsbundle

send data from activity to fragment android studio


I want to send data from activity to fragment, but in fragment data submitted by me is null. I don't know why. this is code when I'm send data and call the fragment.

String b = "hahhaha";
Bundle bundle = new Bundle();
bundle.putString("coba" ,b);
bundle.putSerializable("modelassign" ,modelAssign);

// set Fragmentclass Arguments
ViewTaskFragment vtf = new ViewTaskFragment();
vtf.setArguments(bundle);

//call fragment
FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(R.id.content_frame, new ViewTaskFragment(), "viewtaskfragment");
transact.commit();

and this is code when I'm retrieve the data are sent:

 modelAssign = (ModelAssign) this.getArguments().getSerializable("modelassign");
 String haha = this.getArguments().getString("coba");

Can anyone help?


Solution

  • while adding fragment to transaction, you are creating new instance of ViewTaskFragment(), use already created object in which you have stored bundle.

    transact.add(R.id.content_frame, vtf  , "viewtaskfragment");