bgogetap / StickyHeaders

Easily add Sticky Headers to your RecyclerView
Apache License 2.0
521 stars 88 forks source link

NPE on View.dispatchDetachedFromWindow #87

Open muthuraj57 opened 5 years ago

muthuraj57 commented 5 years ago

I have a fragment which contains FrameLayout with RecyclerView. When I replace or do any transaction on the fragment while a header is stickied in the RecyclerView, getting this crash.

I found the root cause of the crash. I'm setting my adapter as null on onDetachedFromWindow method of RecyclerView to get onDetachedFromRecyclerView callback on my RecyclerView to cleanup some resources (More about this https://github.com/airbnb/epoxy/wiki/Avoiding-Memory-Leaks, I'm not using Epoxy btw).

This calls removeAndRecycleAllViews which in turn calls positioner.clearHeader() which calls detachHeader. Here the header view is removed from the FrameLayout and that's where the issue is. I saw that you already experienced similar issue and handled it through safeDetachHeader by posting the removing process to run on later. I tried the same in detachHeader and it works fine now.

private void detachHeader(int position) {
        if (currentHeader != null) {
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    getRecyclerParent().removeView(currentHeader);
                }
            });
//            getRecyclerParent().removeView(currentHeader);
            callDetach(position);
            currentHeader = null;
            currentViewHolder = null;
        }
    }

Not sure if the fix is correct, hence opening an issue instead of PR.

muthuraj57 commented 5 years ago

Update: This change crashes the app often when header is detached and attached again.