im试图用ListView来实现一个Fragment,该片段采用EditText字段的Input,创建一个对象,然后在ListView上表示这些对象。但是,当我尝试使用ArrayAdapter时,出现NullPointerException。我正在使用一个包含3个String参数的名为“ Event”的对象的ArrayList。我也实现了我自己的arrayAdapter,但在相同的Exception情况下也不起作用。
//onCreateView
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
if(savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
// Button addButton = (Button) getActivity().findViewById(R.id.BtnAddRoommate);
// addButton.setOnClickListener(this);
generateData();
//useListAdapter(container, inflater);
useSimpleAdapter();
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
// arrayAdapter的方法
public void useSimpleAdapter(){
Log.i(TAG, "Simple Adapter in use");
// m_EventList is the ArrayList<Event> that i use
simpleAdapter = new ArrayAdapter<Event>(this.getContext(), android.R.layout.simple_list_item_1, m_EventList);
ListView listView = (ListView) getView().findViewById(R.id.lvEvents);
//lvEvents is the ListView Id from the .xml file.
// Attach the adapter to a ListView
listView.setAdapter(simpleAdapter);
}
XML文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<!-- editTexts and buttons ommited for readability-->
<ListView
android:id="@+id/lvEvents"
android:layout_width="395dp"
android:layout_height="352dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/BtnAddRoommate"
android:layout_marginTop="31dp" />
</RelativeLayout>