0

I have created List view with in Scroll View for that I have created one method to set the height of list view. like below - This method is working fine in API 22 but not in API 18(got null pointer Exception while running in API 18). please give me solution thanks

public static void setListViewHeightBasedOnChildren(ListView listView)
    {
        ListAdapter mAdapter = listView.getAdapter();

        int totalHeight = 0;
        System.out.println("Adapter "+mAdapter);

        for (int i = 0; i < mAdapter.getCount(); i++) {
            View mView = mAdapter.getView(i, null, listView);
            System.out.println("M View "+mView);
            mView.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),

                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

            totalHeight += mView.getMeasuredHeight();
            Log.w("HEIGHT" + i, String.valueOf(totalHeight));

        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
Bogdan Bogdanov
  • 1,707
  • 2
  • 20
  • 31

3 Answers3

4

You should not put a ListView inside ScrollView.

Just refer the below results.

ListView inside ScrollView is not scrolling on Android

Android list view inside a scroll view

Community
  • 1
  • 1
Sridhar
  • 668
  • 1
  • 11
  • 22
0

There is no need to put your listview inside the scrollview .By default listview has scrollview .

0

I have had this error like you. And my solution is following as:

1. Create a custom listview which is non scrollable

public class NonScrollListView extends ListView {

public NonScrollListView(Context context) {
    super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
    super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();    
}

}

2. Use above custom class for xml file

  <com.Example.NonScrollListView
        android:id="@+id/lv_nonscroll_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </com.Example.NonScrollListView>

It worked well on all OS-version for me. Hope best for you.

Hai Rom
  • 1,751
  • 16
  • 9