Reputation: 195
Let's say I'd like to pass data from Fragment A to Fragment B but it throws a nullpointerexception at Fragment B. I'd like to pass the data without use of activity. How do I resolve this?
In FragmentA.java
FragmentB ldf = new FragmentB ();
Bundle args = new Bundle();
args.putString("gender", genderSelected);
args.putString("name", name.getText().toString());
args.putString("contact", contactNo.getText().toString());
args.putString("age", age.getText().toString());
ldf.setArguments(args);
//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.fragmentContainer,ldf).commit();
In FragmentB.java - in onCreateView() method
//Receive data from previous fragment - to be submitted in save
String age = getArguments().getString("age");
String gender = getArguments().getString("gender");
String contact = getArguments().getString("contact");
String name = getArguments().getString("name");
Upvotes: 0
Views: 402
Reputation: 1454
Try to create a static method on your class FragmentB
public static FragmentB newInstance(String gender, String name, String contact, String age) {
FragmentB fragment = new FragmentB();
Bundle args = new Bundle();
args.putString("gender", genderSelected);
args.putString("name", name.getText().toString());
args.putString("contact", contactNo.getText().toString());
args.putString("age", age.getText().toString());
fragment.setArguments(args);
return fragment;
}//newInstance
and
//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.fragmentContainer,FragmentB.newInstance(gender,name,contact,age)).commit();
finally get the datas in your onCreateView() as you did!
Upvotes: 0
Reputation: 361
Your Fragment A is Perfect but in Fragment B you need to change as per following code.
Bundle bundle = this.getArguments();
String age = bundle.getString("age");
String gender = bundle.getString("gender");
String contact = bundle.getString("contact");
String name = bundle.getString("name");
Direct communication between fragment and fragment is not proper way.Refers this link.
Upvotes: 1