-2
如何填充自定義ListView
與來自SQLite database
的數據?
我應該使用哪種類型的適配器?帶CursorAdapter到自定義ListView的SQLite
如何填充自定義ListView
與來自SQLite database
的數據?
我應該使用哪種類型的適配器?帶CursorAdapter到自定義ListView的SQLite
如果你想從SQLite的做ListView
與Data嘗試使用CursorAdapter
。
public class ListAdapter extends CursorAdapter {
public ListAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
return LayoutInflater.from(context).inflate(R.layout.items, parent, false);
}
// The bindView method is used to bind all data to a given view
@Override
public void bindView(View view, Context context, final Cursor cursor) {
TextView txt1 = (TextView) view.findViewById(R.id.TitleLabel);
TextView txt2 = (TextView) view.findViewById(R.id.SecondLabel);
TextView txt3 = (TextView) view.findViewById(R.id.ThirdLabel);
// Extract properties from cursor
// getString(int) - number of column
String value1 = cursor.getString(1);
String value2 = cursor.getString(2);
String value3 = cursor.getString(3);
String value4 = cursor.getString(4);
txt1.setText(value1);
txt2.setText("value2: " + value2);
txt3.setText("value3: " + value3 + "value4: " + value4);
}
}
幫手 - 數據庫輔助類
ListView listview = (ListView) findViewById(R.id.listView);
SQLiteDatabase db = helper.getWritableDatabase();
final Cursor ListCursor = db.rawQuery("SELECT * FROM tablename", null);
final ListAdapter todoAdapter = new ListAdapter(this, ListCursor, 0);
// Attach cursor adapter to the ListView
listview.setAdapter(todoAdapter);
如果你想在列表視圖中顯示單個字段,然後用簡單的Arrayadapter即
DBHelper mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
ListView obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
其他智能實現自定義適配器通過BaseAdapter進行擴展。