有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将listView子对象放在hashmap中

我正在尝试使用for循环从listView获取值,并将它们放入hashmap中。但是logcat不断抛出这个错误。我不明白为什么。请帮忙!列表视图有@安卓: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
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    安卓:id="@安卓:id/list"
    安卓:layout_alignParentTop="true"
    安卓:layout_alignParentLeft="true"
    安卓:layout_alignParentStart="true"
    安卓:layout_marginTop="106dp" />

下面是列表项的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:orientation="vertical" 安卓:layout_width="match_parent"
安卓:layout_height="match_parent">

 <TextView
    安卓:id="@+id/student_name_ls"
    安卓:layout_width="fill_parent"
    安卓:layout_height="wrap_content"
    安卓:paddingBottom="2dip"
    安卓:paddingTop="6dip"
    安卓:textColor="#1e5401"
    安卓:textSize="16sp"
    安卓:textStyle="bold" />

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

问题出在这一行“studentText=(TextView)view.findViewById(R.id.student\u id\u ls);”抛出nullpointerexception请提供任何帮助


共 (1) 个答案

  1. # 1 楼答案

    你应该使用

    listStudent.getChildCount()
    

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