将listView子项放在hashmap中

时间:2016-01-27 08:57:15

标签: java android xml listview

我尝试使用for循环从listView获取值并将它们放在hashmap中。但是logcat不断抛出这个错误。我无法弄清楚原因。请帮忙!列表视图有@android:id / list,我在我的活动上扩展了ListActivity,这是我获取这些值的代码

listStudent=getListView();
studentMarksList=new ArrayList<HashMap<String,String>>();
String student,obtained_value,max_value;
for (int i=0;i<listStudent.getCount();i++) {
    View view=listStudent.getChildAt(i);
    studentIdTxt=(TextView) view.findViewById(R.id.student_id_ls);
    obtainedTxt=(EditText) view.findViewById(R.id.obtained);
    maxTxt=(TextView) view.findViewById(R.id.max);
    student=studentIdTxt.getText().toString();
    obtained_value=obtainedTxt.getText().toString();
    max_value=maxTxt.getText().toString();
    //updating the new mark list array
    HashMap<String,String>studentMark=new HashMap<String,String>();
    studentMark.put(TAG_STUDENT_ID,student);
    studentMark.put(TAG_MARKS_OBTAINED,obtained_value);
    studentMark.put(TAG_MARKS_MAX,max_value);
    studentMarksList.add(studentMark);
}

这是我的列表的xml布局

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@android:id/list"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="106dp" />

,这是列表项的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:id="@+id/student_name_ls"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:paddingTop="6dip"
    android:textColor="#1e5401"
    android:textSize="16sp"
    android:textStyle="bold" />

<!-- Marks label -->
 <EditText
    android:id="@+id/obtained"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:textColor="#acacac"
    android:inputType="numberDecimal"
    android:numeric="decimal" />
 <TextView
    android:id="@+id/max"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:textColor="#0b0b0b"
    android:enabled="false"
    android:editable="false" />
 <TextView
    android:id="@+id/student_id_ls"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:textColor="#060606"
    android:visibility="gone" />
   </LinearLayout>

问题在于这一行&#34; studentIdTxt =(TextView)view.findViewById(R.id.student_id_ls);&#34;抛出nullpointerexception任何帮助请

1 个答案:

答案 0 :(得分:0)

你应该使用

listStudent.getChildCount()

这是因为列表视图中的视图数等于您看到的视图数。它不等于列表视图中的项目数。因此,如果你使用getCount(),你最终会得到一个indexOutOfBoundsException,因为没有更多的视图。