Search code examples
androidandroid-fragmentsfragmentmanager

Android: getSupporteFragment returns null


I always get a null pointer exception on my Log.d. I don't understand why fragmendt is null while its being created just above.

name = "dashboard";
fragment = new FragmentDashboard();

final FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment, name);
transaction.addToBackStack(null);
transaction.commit();

FragmentDashboard fragmendt = (FragmentDashboard) activity.getSupportFragmentManager().findFragmentByTag("dashboard");
Log.d("DEBEUG", "test: " + fragmendt.toString());

Solution

  • FragmentTransaction#commit()'s description reads: "Schedules a commit of this transaction.". This means the fragment is added at some point in the future, but it is not defined when that will be. By directly looking for the fragment afterwards the transaction has not happened yet.

    If you want to force it to immediately create and add the fragment there is the FragmentTransaction#commitNow() method which works synchronously. Do note that you cannot use both addToBackstack(...) and commitNow() looking at the description:

    Transactions committed in this way may not be added to the FragmentManager's back stack, as doing so would break other expected ordering guarantees for other asynchronously committed transactions. This method will throw IllegalStateException if the transaction previously requested to be added to the back stack with addToBackStack(String).