-1

I implements activity with fragments. In every fragment, I implemented RecyclerView. In RecyclerView after every nth row, I attached static view from My singleton class already holding views. In onDestroy of activity I remove all views from GridLayoutManager and remove all Views from RecyclerView and clear adapter objects. After doing all, I clear static views from my singleton class too. But LeakCanary detects memory leak of activity to that particular row. How to avoid memory leaks and how to remove any views holding static context?

    int adPosition = FacebookAdCenter.getInstance().getAdPosition(position);
        View adView;
        if (adPosition >= 0) {
            adView = FacebookAdCenter.getInstance().getNativeAdViewWithAdPosition(adPosition);
        } else {
            adView = null;
        }
        if (adView == null) {
            adView = FacebookAdCenter.getInstance().getNativeAdView(position);
            if (adView.getParent() != null) {
                ((ViewGroup) adView.getParent()).removeView(adView);
            }
            itemView.addView(adView);
        } else {
            if (adView.getParent() != null) {
                ((ViewGroup) adView.getParent()).removeView(adView);
            }
            itemView.addView(adView);
        }

Actually I want to cache Facebook ads to reuse them for an hour. But unfortunately I am still not successful in this. If I use static reference to store ads then there is memory leak. I do not know other ways to cache Facebook ads properly.

Wakil Ahmad
  • 121
  • 5

1 Answers1

0

In RecyclerView after every nth item row view I attached static view from My singleton class already holding views.

Do not do this.

How avoid memory leak

Do not reference views from static fields.

In Java overall, mutable static fields (i.e., not constants) are a code smell. In Android, we tolerate them a bit more, but they are mostly to be used for caches or mediating communications between components. A View cannot be reused between components (activities).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • If I want to hold some data for half an hour in my application without leaking any memory of activity instance, what should I do? – Wakil Ahmad Oct 17 '17 at 15:38
  • @WakilAhmad: Hold onto *data*, not UI widgets, activities, etc. Plain old Java objects (POJOs) are fine, barring size issues. – CommonsWare Oct 17 '17 at 17:19
  • I want to hold facebook native ads. Is it correct? If not, please tell how to cache native ads for an hour? – Wakil Ahmad Oct 17 '17 at 17:22
  • @WakilAhmad: I have not worked with Facebook's ad system, so I do not know if caching them is even appropriate, let alone the rules for doing so safely. Sorry! – CommonsWare Oct 17 '17 at 19:47