I have developed a small API for dialog fragments based on Google support library with very simple requirements:
Does my API creates a memory leakage by constantly adding fragments to backstack?
public class DialogFragmentUtils {
private static final String DIALOG_TAG = "dialogTag";
public static void showDialogFragment(@Nullable Activity activity, @NotNull Fragment fragment) {
if (activity instanceof FragmentActivity) {
FragmentActivity fragmentActivity = (FragmentActivity) activity;
FragmentManager fm = fragmentActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(DIALOG_TAG);
if (prev != null && prev.isAdded()) {
ft.remove(prev);
}
ft.add(fragment, DIALOG_TAG);
ft.addToBackStack(null);
ft.commit();
}
}
public static void dismissDialogFragment(@Nullable Activity activity) {
if (activity instanceof FragmentActivity) {
FragmentActivity fragmentActivity = (FragmentActivity) activity;
FragmentManager fm = fragmentActivity.getSupportFragmentManager();
DialogFragment dialog = (DialogFragment) fm.findFragmentByTag(DIALOG_TAG);
if (dialog != null) {
dialog.dismiss();
}
}
}
}
Yes, its prone to low memory, not memory leak though. All back stack Fragment
are kept in memory with hard references. So if you are keeping a ridiculous amount of Fragment
s in back stack then you will get out of memory.
Have a look here: When a Fragment is replaced and put in the back stack (or removed) does it stay in memory?
UPDATE: I see your DIALOG_TAG
is not changing so you are keeping only one Fragment
in backstack at a time, because you remove old one if it exists. In this case you might not have the issue of low memory.
I believe it wont leak but to be sure you need to test it. As talkol said, you should use Eclipse MAT to analyse this issue. There is a good guide by vogel here and a good guide on the Android blog here. Create and close a bunch of dialogs and see if it makes a difference.
On a side note why do you use ft.close()
instead of prev.dismiss()
in your showDialogFragment()
method. The correct way of closing dialogs is dismiss()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With