erluxman
erluxman

Reputation: 19415

Memory leak while trying to hold a reference of Fragment view beyond onDestoryView()

I want to go from FragmentA (RootFragment) to FragmentB but I do not want to recreate the view of FragmentA once it comes back from FragmentB.

I am using Jetpack Navigation for navigating between Fragments.

To achieve the above goal, I have a fragment Fragment like this:

class RootFragment : DaggerFragment() {
    private var viewToRestore: View? = null


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return if (viewToRestore != null) {
            viewToRestore!!
        } else {
            return inflater.inflate(R.layout.fragment_root, parent, false)
        }
    }

    override fun onDestroyView() {
        viewToRestore = this.view
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
    }    
}

But the FragmentA (RootFragment) is leaking once I reach Fragment B with the attribute viewToRestore.

enter image description here

Any solution that can work without leak but achieve the same goal?

Upvotes: 3

Views: 1805

Answers (2)

Masoud Darzi
Masoud Darzi

Reputation: 650

The problem that you have is a problem for Jetpack navigation as you cannot add when going to another fragment you can just replace:

supportFragmentManager.beginTransaction()
        .replace(R.id.fragment_container, FragmentB.newInstance())
        .addToBackStack(null)
        .commit()

supportFragmentManager.beginTransaction()
        .add(R.id.fragment_container, FragmentB.newInstance())
        .addToBackStack(null)
        .commit()

This is the difference replace and add.

I searched a lot and I guess that jetPack navigation does not support add instead of replace, so I recommend not to use navigation when it's important not to recreate the first fragment

Upvotes: 0

ianhanniballake
ianhanniballake

Reputation: 200130

The leak is a false positive. It is totally fine from a Fragment point of view to hold onto the View you create in onCreateView and return it later, under the condition that your Fragment is not retained or otherwise kept longer than the Context used to create the view is alive.

Upvotes: 7

Related Questions