I have an activity A with 3 fragments. Each fragments replaces each other, hence at a given time only 1 is visible.
HomeFragment has 2 textviews wrapped inside 2 cardviews. Each cardview represents a text value which comes from Fragment1 and Fragment2. When I click on say Card1,I get to the Fragment1.
Fragment1 has some cardviews, when I selects any of them I navigate back to HomeFragment and update the cardview text based on my selection in Fragment1.Here is the switch statement, depending upon what card user selects I put that in a bundle and pass it to HomeFragment.
switch (v.getId()) {
case R.id.card_view0:
Fragment1Bundle.putString("Test", "Testing");
bundle.putBundle("Fragment1Bundle", Fragment1Bundle);
fragmentTransaction.setCustomAnimations(R.anim.slideup, R.anim.slidedown, R.anim.slideup, R.anim.slidedown);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
Fragment2 has same behavior as Fragment 1.
switch (v.getId()) {
case R.id.card_view0:
Fragment2Bundle.putString("Test2", "Tetsing");
bundle.putBundle("Fragment2Bundle", Fragment2Bundle);
fragmentTransaction.setCustomAnimations(R.anim.slideup, R.anim.slidedown, R.anim.slideup, R.anim.slidedown);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
My challenge is that I am using bundles to pass data between fragments, My home fragment gets updated with the data it from fragment1 but when I go to fragment 2 and after making the selection come back to Home fragment, my fragment1 data is set to default. This is what I am doing in Home Fragments onCreateView()
try {
bundle1 = getArguments().getBundle("Fragment1Bundle");
bundle2 = getArguments().getBundle("Fragment2Bundle");
tv.setText(bundle1.getString("Test") == null ? null : bundle1.getString("Test"));
tv2.setText(bundle2.getString("Test2") == null ? nul : bundle2.getString("Test2"));
} catch (NullPointerException e) {
Log.d(TAG, e.printStackTrace());
}
I know that I am creating a new Homefragment in my fragment transaction in both fragment1 and fragment2, How can I keep just 1 instance of Home fragment around.
See Question&Answers more detail:
os