Search code examples
androidbaseadapterhorizontalscrollview

removeAllViews in HorizontalScrollView does not remove views


I am getting few crashes because of this code: (I never got a crash on my devices) The crash is:java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first

Here is the code (I added a try and catch to make sure that this is the code causing the problem):

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    ...
        LinearLayout newView = getItem(position).getNewView();
        HorizontalScrollView hv = (HorizontalScrollView)view.findViewById(R.id.s_scrollview);
        hv.removeAllViews();
        if(newView != null){
            try {
                hv.addView(newView);
            }catch(Exception e){
                e.printStackTrace(); 
// I also send a remote crash log here that is how I confirmed that the crash it is here. I never get a crash on my devices
            }
        }
    ...
    }

This is very frustrating. Anybody have a clue on what is wrong? Thank you!


Solution

  • The problem is that newView already has a parent. The exception says that first the parent should remove its child. That would look like that:

    if(newView != null){
        ((ViewGroup)view.getParent()).removeView(newView);
        hv.addView(newView);
    }