0

I have seen a lot of similar issues with this exception, but it is strange neither of them fits me. I'm not sure where the issue is.

What I have done: I have the Main Activity which is a drawer layout having a bottom navigation bar one of its menus directs to the System Activity(mentioned below) and it has a coordinatorlayout as mentioned below. Inside System Activity, there are a couple of fragments, and every other function works well except when I select an item in the First Fragment (SystemFragList - mentioned below) I get this strange exception.

My Attempt 1: For the first fragment(SystemFragList) of my System Activity I have 1st added a grid view and I wanted to pass the corresponding parameter(like the selected name) to other fragments when I select one grid view item. Grid view was created with a base adapter having an image and a text view. Then when I select one grid item I got below error (same exception).

24034-24034/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 24034
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
    at android.widget.ListView.removeUnusedFixedViews(ListView.java:1908)
    at android.widget.ListView.layoutChildren(ListView.java:1769)
    at android.widget.AbsListView.onLayout(AbsListView.java:2162)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at androidx.viewpager.widget.ViewPager.onLayout(ViewPager.java:1775)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1213)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:899)
    at com.google.android.material.appbar.ViewOffsetBehavior.layoutChild(ViewOffsetBehavior.java:66)
    at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:152)
    at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:43)
    at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1892)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:918)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:446)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)

My Attempt 2: Then I made the grid viwe to a simple list view by converting fragment to list fragment, so that I could find the issue. Now I'm getting the similar exception again.

Error I'm facing:

27490-27490/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 27490
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
    at android.widget.ListView.removeUnusedFixedViews(ListView.java:1908)
    at android.widget.ListView.layoutChildren(ListView.java:1769)
    at android.widget.AbsListView.onLayout(AbsListView.java:2162)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at androidx.viewpager.widget.ViewPager.onLayout(ViewPager.java:1775)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1213)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:899)
    at com.google.android.material.appbar.ViewOffsetBehavior.layoutChild(ViewOffsetBehavior.java:66)
    at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:152)
    at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:43)
    at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1892)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:918)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:446)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:726)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6337)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
    at android.view.Choreographer.doCallbacks(Choreographer.java:686)
    at android.view.Choreographer.doFrame(Choreographer.java:621)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)

I tried: This suggestion and changed "extends AppCompatActivity" to "Extends Activity" but it seems not working for my case.

What I'm looking for: It is strange I cannot find where this casting gets failed. May I know any clue on how to fix this issue or how to trigger the failing point. I found several threads on this same exception but neither one of worked for me since I'm not using a custom adapter. I'm trying the simple version to find out the error.

Codes are as below where my selection fragment and the corresponding XML. I would appreciate any suggestions on this.

SystemFragList : When I select item here I get the exception.

public class SystemFragList extends ListFragment {
    // parameter declrations
public SystemFragList() {
   
}

public interface OnSMDevSelectedListener {
    public void onSMDevSelected(String MLocation, String DevName);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mCallBack = (OnSMDevSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + "nSMDevSelectedListener");
    }
}

public static SystemFragList newInstance() {
    SystemFragList fragment = new SystemFragList();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

public void buildSMsConnectedListView(final List<SMDev> DevList, final Context context){
    if(isVisible()){
        SMDevList = DevList;
        this.context = context;
        if(DevList == null) {
            Log.d("Dev","null");

        }
        else{
            final String[] MList = new String[DevList.size()];
            final String[] displayList = new String[DevList.size()];
            final String[] nameList = new String[DevList.size()];

            for (int i = 0; i < nameList.length; i++) {
                nameList[i] = DevList.get(i).getSMUserAssignedName();
                MList[i] = DevList.get(i).getMId();
                displayList[i] = nameList[i] + "\n" + MList[i];
                          }

            ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(context, R.layout.system_frag_list, displayList);


            setListAdapter(listAdapter);

            final ListView listView = getListView();
            listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectedItemPos = position;

                    selectedDevLocation = MList[position];
                    selectedDevName = nameList[position];
                    selectedDevPos = position;

                    try {
                        mCallBack.onSMDevSelected(MList[position], nameList[position]);
                    } catch (ClassCastException cce) {

                    }
                }
            });

                            if (selectedDevLocation != null) {
                for (int i = 0; i < listView.getAdapter().getCount(); i++) {

                    View view = getView (i, listView);
                    CheckedTextView checkedTextView = (CheckedTextView) view.findViewById(R.id.sys_frag_checked_box);
                    if (checkedTextView != null) {
                        String text = checkedTextView.getText().toString();
                        if (text.contains(selectedDevLocation)) {
                            listView.setItemChecked(i, true);
                        } else {
                            listView.setItemChecked(i, false);
                        }
                    }

                }
            }

        }
    }
}

@Override
public void onResume() {
    if(savedListView != null && savedListAdapter != null) {
        buildSMsConnectedListView(SMDevList, context);
    } else {
        buildSMsConnectedListView(null, getActivity().getApplicationContext());
    }
    super.onResume();
}

public View getView (int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

}

SystemFragList XML

<?xml version="1.0" encoding="utf-8"?>

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sys_frag_checked_box"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeightSmall"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:checkMarkTint="@color/colorPrimary"
    android:paddingRight="?android:attr/listPreferredItemPaddingRight"
    android:paddingLeft="?android:attr/listPreferredItemPaddingLeft" />

SystemAcivity : Activity corresponding to Fragment. This is one of the menu items of bottom navigation bar in the Main Activity

public class SystemActivity extends AppCompatActivity implements SystemFragList.OnSMDevSelectedListener,EnableSenFrag.OnSenSelectedListener {
        
 //… Other functions & fragment new instance


    @Override
    public void onSMDevSelected(String MLocation, String DevName) {

        if(!mService.getSM(MLocation).isLive()){
            Toast.makeText(this, "Selected " + DevName + "\n" + MLocation, Toast.LENGTH_SHORT).show();
            selectedDevLocation = MLocation;
            selectedDevName = DevName;

            //Pass the selected Dev to the fragments
            SMDev Dev = mService.getSM(selectedDevLocation);
            enableSenFrag.setSMService(mService);
            enableSenFrag.buildSenList(Dev, this, mService.getBluetoothManager());

            configurationFrag.buildDevConfigList(Dev, this, mService.getBluetoothManager());

            } else{
            Toast.makeText(this, "Selected " + DevName + " " + “Unable to select!", Toast.LENGTH_SHORT).show();
        }

    }

SystemActivity XML

  <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager_system_activity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        >

      <androidx.viewpager.widget.PagerTabStrip
            android:id="@+id/pager_title_strip"
            android:layout_width="wrap_content"
            android:layout_height="45dp"
            android:layout_gravity="top"
            android:background="@color/colorPrimary"
            android:paddingTop="4dp"
            android:paddingBottom="4dp"
            android:textColor="@color/colorAccent" />
    </androidx.viewpager.widget.ViewPager>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Update : 2 Fragments having footers

EnableSenFrag: This is a simple List Fragment having a footer with a button.

    public class EnableSenFrag extends ListFragment {

// other parameters
Button button ;
boolean buttonAvailable =false;

// function related to adding a footer
public void buildSenList(final SMDev SMDev, final Context activityContext,
                                 final SMBluetoothManagerAndroid bluetoothManager) {

        if(!SMDev.isLive()) {
// .. creating an arrays and data for the list here
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(activityContext, R.layout.enable_sen_list_checkedtext_item, arraySen);
            setListAdapter(adapter);

            final ListView listView = getListView();
            listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);


            //if (listView.getFooterViewsCount() == 0 || buttonAvailable==false) {
            if (buttonAvailable==false) {   //Only add the button if there is no existing button
                //Create button in the ListView footer
                listView.removeFooterView(button); // remove the previously added footer if avilable
                button = new Button(activityContext);
                button.setText("OK");
                button.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.WRAP_CONTENT, ListView.LayoutParams.WRAP_CONTENT));
                listView.addFooterView(button);
                button.setTextColor(Color.parseColor("#ee669b"));
/*            if (SMDev.isLive()){
                button.setEnabled(false);
                button.setVisibility(View.GONE);
            }*/
                button.setEnabled(true);
                button.setVisibility(View.VISIBLE);
                buttonAvailable=true;
                button.setOnClickListener(new View.OnClickListener() {
                  // ..button on click functions here 
    );

            }

            updateCheckboxes(listView, count);

            
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                  // list view item on click functions here
);
        }else{
            setDevNotLiveView();
        }
    }

public void setDevNotLiveView() {
    String[] values = new String[] {"Devs are not Live"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),  R.layout.enable_sen_list_item, values);
    setListAdapter(adapter);
    if(buttonAvailable){
        button.setEnabled(false);
        button.setVisibility(View.GONE);
    }
    buttonAvailable=false;
}

ConfigurationFrag: This has a linear layout with a TextView, Button, and Expandable list view having a footer for buttons.

public class ConfigurationFrag extends Fragment {

    //parameters declaration and other initial functions’=
    // function adding footers

    public void buildDevConfigList(final SMDev SMDev, final Context context,
                                      final SMBluetoothManagerAndroid bluetoothManager) {

        if(SMDev!=null){
        DevNameTV = (TextView) getView().findViewById(R.id.config_dev_name);
        setRateBtn = (Button) getView().findViewById(R.id.setRateBt);

    //.. create data list

        expandListAdapter = new ConfigDevListAdapter(context, listOfKeys, configOptionsMap, SMDev, SMDevClone);
        expandListView = (ExpandableListView) getView().findViewById(R.id.config_expandable_listview);
        expandListView.setAdapter(expandListAdapter);

        expandListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
//..onclick functions here  
        });

        //Only add the buttons if they haven't added previously        if(expandListView.getFooterViewsCount() == 0) {
            LinearLayout buttonLayout = new LinearLayout(context);
            buttonLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
            buttonLayout.setGravity(Gravity.CENTER);
            buttonLayout.setPadding(10,10,10,10);
            Button writeConfigButton = new Button(context);
            Button resetListButton = new Button(context);

            writeConfigButton.setOnClickListener(new View.OnClickListener() {
                        //writeButton On click functions
                
            });
            resetListButton.setOnClickListener(new View.OnClickListener() {
                         //resetButton On click functions   });

            writeConfigButton.setText("Write");
            resetListButton.setText("Reset ");
            writeConfigButton.setTextColor(Color.parseColor("#ee669b"));
            resetListButton.setTextColor(Color.parseColor("#ee669b"));
            buttonLayout.addView(resetListButton);
            buttonLayout.addView(writeConfigButton);
            expandListView.addFooterView(buttonLayout);
        }
        DevNameTV.setText(SMDev.getSMUserAssignedName()+ " " + "Unit");
        setRateBtn.setOnClickListener(new View.OnClickListener() {
                         //button On click functions   
        });

        }
        else{
            Log.d(" Dev is: ","null");
        }
            }



    public void setDevUnavailableView(Context context) {
        DevNameTV = (TextView) getView().findViewById(R.id.config_dev_name);
        setRateBtn = (Button) getView().findViewById(R.id.setRateBt);
        expandListView = (ExpandableListView) getView().findViewById(R.id.config_expandable_listview);
        SimpleExpandableListAdapter mAdapter;
        
        String groupItems[] = {"Dev is unavailable"};
        String[][] childItems = {{"Configuration is impossible"}};

        List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
        List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();

        for (int i = 0; i < groupItems.length; i++) {
            Map<String, String> curGroupMap = new HashMap<String, String>();
            groupData.add(curGroupMap);
            curGroupMap.put("NAME", groupItems[i]);
            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
            for (int j = 0; j < childItems[i].length; j++) {
                Map<String, String> curChildMap = new HashMap<String, String>();
                children.add(curChildMap);
                curChildMap.put("NAME", childItems[i][j]);
            }
            childData.add(children);
        }

        String groupFrom[] = {"NAME"};
        int groupTo[] = {R.id.heading};
        String childFrom[] = {"NAME"};
        int childTo[] = {R.id.childItem};

        mAdapter = new SimpleExpandableListAdapter(context, groupData,
                R.layout.nosignal_group_item,
                groupFrom, groupTo,
                childData, R.layout.nosignal_child_item,
                childFrom, childTo);
        expandListView.setAdapter(mAdapter);
        expandListView.setGroupIndicator(null);

        DevNameTV.setText("Select a Dev");
        setRateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "SM Dev is unavailable", Toast.LENGTH_SHORT).show();
            }
        });
8
  • 1
    Are you sure that Fragment is where the issue is? That stack trace indicates that the ListView causing the Exception has at least one header or footer View added (improperly), but I don't see that anywhere in the given code. Commented Jun 30, 2020 at 19:27
  • 1
    Oh, I'm sorry, I just noticed that you said it happens when you select an item in that Fragment. It's possibly happening in that callback, then. In any case, it's a ListView somewhere that has a header and/or footer. Commented Jun 30, 2020 at 19:50
  • 1
    buttonLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); – That's your problem, in ConfigurationFragment. Those should be ListView.LayoutParams, rather than LinearLayout.LayoutParams; like you have it in EnableSenFrag. Commented Jun 30, 2020 at 21:53
  • 1
    Woohoo! Thank you very much for the support @MikeM.! Now it is working. I spent a lot of time to trigger the issue. Wow! Just for my knowledge: May I know why is that happening when there is LinerLayout but not the ListView. How did you think that the error is related to the footer/header? Thanks again! Commented Jun 30, 2020 at 22:15
  • 1
    A View's LayoutParams will be of its parent's type, not its own. That is, since those footers are in a ListView, they need ListView.LayoutParams. LayoutParams are information for the parent to know how to layout the child, so they need to be the parent's type. As far as knowing that it was a header or footer causing the issue, I've tracked this error down before, on a previous question here. Anyhoo, glad you got it working. Cheers! Commented Jun 30, 2020 at 22:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.