Leak canary, Recyclerview leaking mAdapter

前端 未结 4 1240
我寻月下人不归
我寻月下人不归 2021-01-30 16:33

I decided it was high time I learned how to use Leak Canary to detect Leaks within my apps, and as I always do, I tried to implement it in my project to really understand how to

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 17:32

    First of all, I'm referencing this file.

    It looks like v7.widget.RecyclerView is leaking the adapter, and not my application. But that can't be right.... right?

    It's actually your adapter that's leaking the RecyclerView (and it's made pretty clear by the trace graph and the title of the LeakCanary activity). However, I'm not sure if it's the "parent" RecyclerView or the nested one in the HourlyViewHolder, or both. I think the culprits are your ViewHolders. By making them non-static inner classes, you explicitly provide them with the reference to the enclosing adapter class, ant this almost directly couples the adapter with the recycled views, since the parent of every itemView in your holders is the RecyclerView itself.

    My first suggestion to fix this problem would be to decouple your ViewHolders and Adapter by making them static inner classes. That way they do not hold a reference to the adapter, so your context field will be inaccessible to them, and it's also a good thing, since context references should be passed and stored sparingly (also to avoid big memory leaks). When you need the context just to obtain the strings, do it somewhere else, for example in the adapter constructor, but do not store the context as a member. Finally, the DayForecastAdapter seems dangerous too: you pass the one, same instance of it to every HourlyViewHolder, which seems like a bug.

    I think that fixing the design and decoupling these classes should get rid of this memory leak

提交回复
热议问题