2

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?

OldMcDonald
  • 594
  • 13
  • 36
Fania Indah
  • 135
  • 1
  • 3
  • 11

3 Answers3

1

You're passing the arguments bundle into a Fragment:

ViewTaskFragment vtf = new ViewTaskFragment();
vtf.setArguments(bundle);

but then creating a new Fragment for the transaction:

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

Use the Fragment you've previously created that contains the arguments:

transact.add(R.id.content_frame, vtf, "viewtaskfragment");
Egor
  • 39,695
  • 10
  • 113
  • 130
1

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");
Ravi
  • 34,851
  • 21
  • 122
  • 183
0

Change this

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

to

transact.add(R.id.content_frame, vtf, "viewtaskfragment");
fluffyBatman
  • 6,524
  • 3
  • 24
  • 25