Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backstack and memory leakage

I have developed a small API for dialog fragments based on Google support library with very simple requirements:

  • API could add (or replace) a modal dialog
  • API could dismiss dialog programmatically or user can dismiss dialog by pressing button

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();
        }
    }
}
}
like image 820
Nulldevice Avatar asked Mar 23 '23 02:03

Nulldevice


2 Answers

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 Fragments 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.

like image 191
M-WaJeEh Avatar answered Apr 21 '23 07:04

M-WaJeEh


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().

like image 26
Warpzit Avatar answered Apr 21 '23 05:04

Warpzit