Android数据显示之ListView
1.使用SimpleAdapter
List<Person> persons = personService.getScrollData(0, 5); //构造SimpleAdapter的参数类型 List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); //把Person数据放到HashMap当中去 for(Person person : persons) { HashMap<String, Object> item = new HashMap<String, Object>(); item.put("id", person.getId()); item.put("name", person.getName()); item.put("amount", person.getAmount()); data.add(item); } //把数据绑定到SimpleAdapter SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, new String[]{"id", "name", "amount"}, new int[]{R.id.id, R.id.name, R.id.amount}); listView.setAdapter(adapter); //设置ListView点击事件响应 listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView lView = (ListView)parent; HashMap<String, Object> item = (HashMap<String, Object>)lView.getItemAtPosition(position); Toast.makeText(MainActivity.this, item.get("id").toString(), 1).show(); } });
public List<Person> getScrollData(Integer offset, Integer maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from person limit ?,?", new String[]{offset.toString(), maxResult.toString()}); while(cursor.moveToNext()) { int personid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); int amount = cursor.getInt(cursor.getColumnIndex("amount")); Person person = new Person(personid, name); person.setAmount(amount); persons.add(person); } cursor.close(); return persons; }
2.使用SimpleCursorAdapter
//获取前五项数据,注意这里Cursor里面必须有"_id",否则Cursor不会工作 Cursor cursor = personService.getCursorScrollData(0, 5); //使用SimpleCursorAdapter SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, new String[]{"_id", "name", "amount"}, new int[]{R.id.id, R.id.name, R.id.amount}); listView.setAdapter(adapter); //设置ListView点击事件响应 listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView lView = (ListView)parent; //把当前位置强制转换为Cursor Cursor data = (Cursor)lView.getItemAtPosition(position); //获取当前item的位置信息 int personid = data.getInt(data.getColumnIndex("_id")); //显示出当前item的id信息 Toast.makeText(MainActivity.this, personid+"", 1).show(); } });
//注意这里的personid as _id,是因为Cursor里面必须有_id
public Cursor getCursorScrollData(Integer offset, Integer maxResult) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); //注意这里的personid as _id,是因为Cursor里面必须有_id return db.rawQuery("select personid as _id, name, amount from person limit ?,?", new String[]{offset.toString(), maxResult.toString()}); }