[Android] 將SQLite查詢到的資料顯示在listview上

lv1 = (ListView)findViewById(R.id.lv1);

db = openOrCreateDatabase(“db1.db”,MODE_PRIVATE,null); 
Cursor cursor = db.rawQuery(“select _id, name, phone from mytable”,null);

if (cursor != null && cursor.getCount() >= 0) {

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[]{“name”, “phone”}, new int[]{android.R.id.text1, android.R.id.text2}, 0);
lv1.setAdapter(adapter);

}

但預設的simple_list_item_2只能放二個欄位,但我有三個欄位要顯示的話,該怎麼辦呢??

有一個取巧的方法,在SQL的語法上動手腳,範例如下

lv1 = (ListView)findViewById(R.id.lv1);

db = openOrCreateDatabase(“db1.db”,MODE_PRIVATE,null);

Cursor cursor = db.rawQuery(“select _id, _id||’.’||name sname, phone from mytable”,null);

if (cursor != null && cursor.getCount() >= 0) {

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[]{“sname”, “phone”}, new int[]{android.R.id.text1, android.R.id.text2}, 0);

lv1.setAdapter(adapter);

}

如果我們使用button或其他元件改變SQLite的內容後,要即時顯示改變後的內容,做法如下

cursor.requery();
lv1.setAdapter(adapter);

當我們將SQLite的資料放到listview裡面,有些情況會需要點listview的item時將資料抽出,這時的做法是

lv1.setOnItemClickListener(itemClickListener); //這行放到onCreate()裡

private ListView.OnItemClickListener itemClickListener = new ListView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            cursor.moveToPosition(position);
            Integer iid = cursor.getInt(0);
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            editText.setText(String.valueOf(iid));
            editText2.setText(name);
            editText3.setText(phone);
        }
    };

Comments |0|

Legend *) Required fields are marked
**) You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Category: 來玩Android