单击listview项时检索的值

时间:2015-08-24 00:31:37

标签: android sqlite listview android-listview

我使用适配器创建了一个listview。 listview包含表中特定字段的不同值。现在,当单击listview项时,它应该检索具有该特定数据的id的所有项。我设法从列表视图中获取数据,但是当项目未正确获取时。

row.xml

    <ImageView
    android:id="@+id/img"
    android:src="@mipmap/ic_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

    <TextView
    android:id="@+id/txtid"
    android:layout_marginTop="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="sd"
    />

Tab2.java

 ListView list;
    final ArrayList<HashMap<String, String>> mylist;
    ListAdapter adapter;
    HashMap<String, String> map2;
   final TextView a1;
    list = (ListView) v.findViewById(R.id.listView2);
    a1 = (TextView) v.findViewById(R.id.txt1);
    mylist = new ArrayList<HashMap<String, String>>();

    DatabaseHandler db = new DatabaseHandler(getActivity());
    final List<Product> sent = db.getSentProducts();
    for (Product s : sent) {
        map2 = new HashMap<String, String>();
        map2.put("txtid", s.getMsg_id());
        mylist.add(map2);
        Log.d("msgid", s.getMsg_id());
    }
    for (Product s : sent) {
    }
    try {
        adapter = new SimpleAdapter(getActivity(),mylist,R.layout.sent_row, new String[]{"txtid"}, new int[]{R.id.txtid});
        list.setAdapter(adapter);
    } catch (Exception e) {
    }


    list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            TextView a = (TextView)v.findViewById(R.id.txtid);
            String content1 = a.getText().toString();
            DatabaseHandler db = new DatabaseHandler(getActivity());
            List<Product> sentinfo =  db.getSentProductInfo(content1);

           for (Product si : sentinfo){

                   Log.d("asdsd", si.getStorCode()+" "+si.getCode()+" "+si.getBstock()+" "+si.getDeliveries()+" "+si.getSpoilage()+" "+ si.getEstock()+" ");
          }

            return true;
        }
    });
    return v;
}

分贝

enter image description here

android ui

enter image description here

当我在listview中单击20150824070159时,它应该在表中获取两行,但是,它只获取一行,而它是另一个id的数据,20150820162104。

我将如何回答这个问题?

1 个答案:

答案 0 :(得分:1)

要从列表视图中单击项目获取文本,您应该这样做:

 list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

           String clickedText = list.getItemAtPosition(position).toString();                

        }
    });

请确保在任何方法之外的全局范围内声明list变量,因为在onCreate或任何其他方法已经结束后将调用此函数。