0

I am working on a pretty big app (about 70 fragments). When I click through my app, all my previous fragments are stored in the backstack. After some clicks my memory is pretty high and on old phones (Samsung S3) I get an OutOfMemory exception.

Is there a way to do something about the memory usage of the fragment backstack? I already tried to make my own backstack, it fixed the memory problem but the only problem was that it doesn't remember search terms and scrolling positions this way:

Stack<BackStackEntry> mBackStack = new Stack<>();
mBackStack.add(new BackStackEntry(tag, fragment.getClass()));
Bart Bergmans
  • 4,061
  • 3
  • 28
  • 56

2 Answers2

0

You can use SingleTone pattern for your fragments. At least will be reduce memory for sure because you dont must to recreate your fragments everytime when you call at or add it in back stack

 // Singleton implementation
    private static YourFragment instance;

    public YourFragment () {
    }

    /**
     * Static method which return the instance of the fragment. If the fragment is null, load it,
     * else create new fragment. Singleton pattern.
     *
     * @param context
     * @return
     */
    public static YourFragment getInstance() {
        if (instance == null) {
            instance = new YourFragment ();
        }

        return instance;
    }

and you can access your fragment with this line of code:

SearchFragment.getInstance()
Kristiyan Varbanov
  • 2,439
  • 2
  • 17
  • 37
0

In very special situations, you can request a larger heap size by setting the largeHeap attribute to "true" in the manifest tag. Never request a large heap simply because you've run out of memory and you need a quick fix—you should use it only when you know exactly where all your memory is being allocated and why it must be retained.

Read https://developer.android.com/training/articles/memory.html

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • I want to prevent that – Bart Bergmans Mar 29 '16 at 14:18
  • @BartBergmans it is good!) Have you seen this link, maybe it can help you http://stackoverflow.com/questions/28483600/android-fragments-on-backstack-taking-up-too-much-memory – Roman Havran Mar 29 '16 at 14:31
  • Actually android:largeHeap is the instrument for increasing your allocated memory to app. There is no clear definition of the need to use this flag. If you need more memory - Android provides you with a tool to increase it. But necessity of using, you define yourself. – Stanojkovic Mar 29 '16 at 14:54