Android:将适配器添加到ListView时出现NullPointerException

时间:2016-10-26 19:00:47

标签: java android android-layout listview nullpointerexception

我正在activity_table.xml创建一个ViewPager。

此ViewPager有两个页面,它们共享相同的布局:list.xml 此布局包含ListView,我正在尝试为其创建适配器。

应用程序正确编译但在尝试将所述适配器添加到带有

ListView时崩溃
  

尝试在空对象引用上调用虚方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'时出现NullPointerException。

我听说在使用它包含的视图之前我必须“加载”一个布局,但我该怎么做?

我已经尝试了setContentView(R.layout.list),但它会抛出同样的错误......

Table.java

    SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    ViewPager viewPager = (ViewPager) findViewById(R.id.container);
    viewPager.setAdapter(sectionsPagerAdapter);

    String[] tmp = new String[mainTable.length-2];
    ListView listView = (ListView)findViewById(R.id.listView);
    ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
    listView.setAdapter(listAdapter);

public static class TableFragment extends Fragment {
    private static final String ARG_SECTION_NUMBER = "section number";

    public TableFragment() {
    }
    public static TableFragment newInstance(int sectionNumber) {
        TableFragment fragment = new TableFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER,sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.list,container,false);
        TextView title = (TextView) rootView.findViewById(R.id.title);

        if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
            title.setText("Heute");
        else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
            title.setText("Morgen");

        return rootView;
    }
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return TableFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "today";
            case 1:
                return "tomorrow";
        }
        return null;
    }
}


public class ListAdapter extends ArrayAdapter<String> {
    public ListAdapter(Context context, int textViewResourceId) {
        super(context,textViewResourceId);
    }
    public ListAdapter(Context context, int resource, String[] items) {
        super(context,resource,items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        if(v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.list_item, null);
        }

        String p = getItem(position);

        if(p!=null) {
            TextView grade = (TextView) v.findViewById(R.id.grade);
            TextView hour = (TextView) v.findViewById(R.id.hour);
            TextView course = (TextView) v.findViewById(R.id.course);
            TextView teacher = (TextView) v.findViewById(R.id.teacher);
            TextView room = (TextView) v.findViewById(R.id.room);
            TextView description = (TextView) v.findViewById(R.id.description);

            try {
                grade.setText(tableData[position][1]);
                hour.setText(tableData[position][2]);
                course.setText(tableData[position][3]);
                teacher.setText(tableData[position][4]);
                room.setText(tableData[position][5]);
                description.setText(tableData[position][6]);
            } catch (ArrayIndexOutOfBoundsException e) {
                return v;
            }
        }

        return v;
    }
}

activity_table.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="de.fuchstim.vertretungsplan.Table">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:layout_gravity="bottom|right"
        app:srcCompat="@drawable/reload_arrow_white" />


</android.support.design.widget.CoordinatorLayout>

list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:text="Heute (25.10.16)"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:textAppearance="@android:style/TextAppearance.DeviceDefault.DialogWindowTitle"
    android:textAlignment="center" />

<GridLayout android:layout_gravity="start"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/grade"
        android:layout_height="wrap_content"
        android:text="Klasse"
        android:layout_row="0"
        android:layout_column="0"
        android:layout_width="0dp"
        android:textSize="14sp"
        android:layout_columnWeight="40"
        android:paddingStart="10dp" />

    <TextView
        android:text="Stunde"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/hour"
        android:layout_row="0"
        android:layout_column="1"
        android:layout_columnWeight="15"/>

    <TextView
        android:text="Lehrer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/teacher"
        android:layout_row="0"
        android:layout_column="3"
        android:layout_columnWeight="15"/>

    <TextView
        android:text="Kurs"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/course"
        android:layout_row="0"
        android:layout_column="2"
        android:layout_columnWeight="15"/>

    <TextView
        android:text="Raum"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/room"
        android:layout_row="0"
        android:layout_column="4"
        android:layout_columnWeight="15"/>

</GridLayout>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:id="@+id/listView" />

</LinearLayout>

2 个答案:

答案 0 :(得分:0)

  

我尝试过setContentView(R.layout.list),但它会抛出相同的错误......

首先,您需要使用setContentView(R.layout.activity_table)

其次,您无法从Activity中找到ListView,因为它包含在Fragment布局中。

看到这里?您的ListView与此title元素的布局相同,因此您需要在此处找到ListView ...

View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);

将ListView代码从Activity移动到Fragment。并使用getActivity()作为片段中的适配器而不是this来获取上下文。

这是@+id/listView值存在的位置。使用rootView.findViewById搜索该布局。

答案 1 :(得分:0)

因为,你没有在这个位置得到空指针:

ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(sectionsPagerAdapter);

所以,这意味着你正在使用:

setContentView(R.layout.activity_table);

因为viewpager只在上面的布局中,并且由于listview不在这个布局xml文件中,所以你得到空指针:

ListView listView = (ListView)findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
listView.setAdapter(listAdapter);

因为listview为null,不存在于activity_table xml文件中。

您需要在OnCreateView()中设置适配器:

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.list,container,false);
    TextView title = (TextView) rootView.findViewById(R.id.title);

    // Add below ...
    String[] tmp = new String[mainTable.length-2];
    ListView listView = (ListView)rootView.findViewById(R.id.listView);
    ListAdapter listAdapter = new ListAdapter(getActivity(),R.layout.list_item,tmp);
    listView.setAdapter(listAdapter);

    // ends here ...

    if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
        title.setText("Heute");
    else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
        title.setText("Morgen");

    return rootView;
}

希望这有帮助!