ListView listView = (ListView)container.findViewById(R.id.listView); ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_one, container, false); String[] datasource = {"aaaa", "bbbb", "cccc"}; final ArrayAdapter<String> adapter; adapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_list_item_1, R.id.text1, datasource); listView.setAdapter(adapter); 

When I run the application, a java.lang.NullPointerException error appears in the listView.setAdapter(adapter);

Here is the xml of the fragment on which the ListView

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" xmlns:card_view="http://schemas.android.com/apk/res-auto" tools:context="com.andrew.mpd.fragments.OneFragment"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/listView" /> </ScrollView> 

What did I miss or do wrong?

  • What container ? Why is it before loading markup? And never wrap a ListView in ScrollView - YuriiSPb

1 answer 1

 ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_one, container, false); ListView listView = (ListView)rootView .findViewById(R.id.listView); 

And never wrap a ListView in ScrollView.

  • Why not to wrap in ScrollView? - andrew
  • @andrew, you can just try) You will only have one list item displayed, because ListView itself is a scrolling markup element and conflicts with ScrollView when calculating the height of individual elements. This can be bypassed with a dirty hack, but it is better not to try to do it. - YurySPb