If I'm adding fragments to my activity like this:
fragment_tags = new ArrayList<String>();
fragment_tags.add("user_fragment");
fragment_tags.add("memorial_fragment");
UserFragment user = new UserFragment();
MemorialFragment memorial = new MemorialFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.content_frame, user, fragment_tags.get(0));
ft.add(R.id.content_frame, memorial, fragment_tags.get(1));
ft.commit();
and then after some time I'm trying to retrieve these fragments like this:
List<Fragment> frg = getSupportFragmentManager().getFragments();
Fragment fragUser = getSupportFragmentManager().findFragmentByTag(
"user_fragment");
Fragment fragUserID = getSupportFragmentManager().findFragmentById(
R.id.user_fragment_id);
Log.d("MV", "fragments size:" + (frg == null ? " null" : frg.size()));
Log.d will always return size of 2, but fragUser is sometimes null and sometimes it's the fragment I put in transaction.
Which is more interesting is that this code:
try {
Log.d("MV", "0:" + frg.get(0).toString());
Log.d("MV", "1:" + frg.get(1).toString());
} catch (NullPointerException e) {
Log.d("MV", "null caught");
}
will sometimes work for both fragments and sometimes just for the first and if i do smething like this:
if(frg.get(0) == fragUser)
it will be sometimes evaluated as true, but not often.. I don't really understand this behaviour, but I need to implement switching between multiple fragments, so I need to get reference to exact fragment. Anybody? I'm trying to solve this for 6 hours now and I really dont understand how to do this. Thank you