I want to pass a complex object between activity and fragments as well as fragments and fragments. Currently, the main activity create a fragment input object and set that as a member of the fragment needed to be open. Similarly, when another fragment wants to load another fragment it creates fragment input and notifies the main activity. See Main and child fragment code below. My question, is this correct implementation. Sometimes I encountered input being null in child activity, if the activity pauses and restarts.
Please tell me what I have done wrong, whats the best way to pass data.
public class FragmentInput {
public String url = "";
public String title = "";
public String time = "";
... other memebers
}
Main Activity
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
BaseFragment fragment = new LandingFragment();
**FragmentInput input = new FragmentInput();
input.stringinput = stringinput;
fragment.input = input;
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();**
public void replaceFragment(BaseFragment fragment) {
if (fragment == null)
return;
if (fragment instanceof firstFragment) {
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.setCustomAnimations(0, 0);
fragmentManager.popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
String ttag = fragment
.getClass().toString();
Fragment tempF = fragmentManager.findFragmentByTag(ttag);
if (tempF != null)
return;
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_enter,
R.anim.fragment_exit, R.anim.fragment_leftenter,
R.anim.fragment_leftexit);
fragmentTransaction.replace(R.id.fragment, fragment, ttag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
ChildFragment
@Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
try {
activity = getActivity();
resource = activity.getResources();
view = getView();
**if (input != null) {
String url= input.url;**
button.onclick(){
FragmentInput input = new FragmentInput();
input.url = path;
input.title = resource.getString(R.string.txt_from_gallery);
**BaseFragment fr = new otherFragment();
FragmentChangeListener fc = (FragmentChangeListener) getActivity();
fr.setInput(input);
fc.replaceFragment(fr);**
}
}