user2546015
user2546015

Reputation: 3

NullPointerException on listview.getCount() method

Application crashes throwing null pointer exception on line RoomList.getAdapter().getCount(). I need to fetch each edit Text value from listview and apply some computations on it, after searching various posts, I have found out this solution but it is not working properly.

RoomList = (ListView) vi.findViewById(R.id.list2);
for (int i = 0; i < RoomList.getAdapter().getCount(); i++) {
        View view = RoomList.getChildAt(i);
        EditText edit = (EditText) view.findViewById(R.id.editRoom);
        Log.d("value from each edit text", edit.getText().toString());
}

Upvotes: 0

Views: 758

Answers (2)

Gomino
Gomino

Reputation: 12347

The problem is that your are accessing your list's adapter without first setting it.

RoomList = (ListView) vi.findViewById(R.id.list2);
RoomList.setAdapter(new SubClassOfBaseAdapter()); // <-- setup your adapter here, with anArrayAdapter or a sublass of BaseAdapter
for (int i = 0; i < RoomList.getAdapter().getCount(); i++) {
    View view = RoomList.getChildAt(i);
    EditText edit = (EditText) view.findViewById(R.id.editRoom);
    Log.d("value from each edit text", edit.getText().toString());
}

Upvotes: 0

Adam Stelmaszczyk
Adam Stelmaszczyk

Reputation: 19837

You have NPE because RoomList.getAdapter() returns null. Maybe you didn't call RoomList.setAdapter(ListAdapter adapter).

By the way, you should change the name RoomList to roomList, to stick to Java convention. RoomList.getAdapter() at first glance looks like a static method call of some RoomList class.

Upvotes: 1

Related Questions