Reputation: 6899
I am doing service call in FragmentActivity
where I need to pass two datas(name and address) to Fragment A and Fragment B respectively.
Here is my code which I tried.
public class C extends FragmentActivity {
// public PassDataToFragments fragmentCommunicator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.detail_pager);
serviceCall();
}
void serviceCall() {
JSONObject totalData = new JSONObject(result);
JSONObject jsonData = totalData.getJSONObject("result");
trainerStrName = jsonData.getString("name");
trainerStrAddress = jsonData.getString("address");
// activityCommunicator.passDataToFragment(trainerStrName); i am
// null pointer exception
// pass name to fragment A and address to fragment B
}
@Override
public SherlockFragment getItem(int arg0) {
switch (arg0) {
// Open Previous Projects
case 0:
FragmentA fragmentA = new FragmentA ();
return fragmentA;
// Open Certification
case 1:
FragmentB fragmentB = new FragmentB ();
return fragmentB;
}
return null;
}
}
What I tried is I used interface but i don't know how to use and get the values of name to FragmentA and address to Fragment B:
public interface PassDataToFragments {
public void passDataToFragment(String someValue);
}
class Fragment A extends Fragment implement PassDataToFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.trainers_certification,
container, false);
return view;
}
@Override
public void passDataToFragment(String someValue) {
//Log.e("string",someValue);
}
}
Upvotes: 0
Views: 1523
Reputation: 7306
You can simply access the Activity's data by calling Activity's method from fragment :
Get the value in Fragment :
String name = ((C)getActivity()).getValue();
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT);
C Class :
public String getValue()
{
return trainerStrDescription;
}
Hope it helps ツ
Upvotes: 0
Reputation: 18112
Pass the data from activity like this
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("address", address);
FragmentA fragmentA = new FragmentA();
fragmentA.setArguments(bundle);
and in Fragment A onCreateView
method retrieve it like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
String name = getArguments().getString("name");
String address = getArguments().getString("address");
}
EDIT
If fragment is already loaded then you can do it like this (using your current implementation)
Send data like this
PassDataToFragment fragA = (PassDataToFragment) getSupportFragmentManager().findFragmentById(R.id.container); // Change the id as per yours
fragA.passDataToFragment(name, address);
You will get the data in passDataToFragment()
inside fragment A.
Upvotes: 1