Bad*_*ari 1 sqlite android android-listview
我正在尝试从我的SQLite数据库填充listview ...这是我从数据库获取数据的方式:
Cursor c = database.rawQuery("SELECT * FROM " + TableName, null);
int Column1 = c.getColumnIndex("uri");
int Column2 = c.getColumnIndex("file");
int Column3 = c.getColumnIndex("id");
c.moveToFirst();
if (c != null) {
do {
String uri = c.getString(Column1);
String file = c.getString(Column2);
int id = c.getInt(Column3);
} while (c.moveToNext());
}
Run Code Online (Sandbox Code Playgroud)
我通常会向listview添加一个数组:
ListView my_listview2 = (ListView) findViewById(R.id.listView1);
String my_array[] = {"Android", "iPhone"};
my_listview2.setAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.my_custom_row, my_array));
Run Code Online (Sandbox Code Playgroud)
如何从我的SQL查询中创建一个数组来setadapter?
执行此操作的最佳方法是使用CursorAdapter或SimpleCursorAdapter.这将为您提供最佳性能,一旦您弄明白,您会发现使用SQLite数据库时这是最简单的方法.
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
下面是我经常使用的简单CustomCursorAdapter.只需将CustomCursorAdapter类添加为内部类.
protected class CustomCursorAdapter extends SimpleCursorAdapter {
private int layout;
private LayoutInflater inflater;
private Context context;
public CustomCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.layout = layout;
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Log.i("NewView", newViewCount.toString());
View v = inflater.inflate(R.layout.list_cell, parent, false);
return v;
}
@Override
public void bindView(View v, Context context, Cursor c) {
//1 is the column where you're getting your data from
String name = c.getString(1);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.textView);
if (name_text != null) {
name_text.setText(name);
}
}
Run Code Online (Sandbox Code Playgroud)
像这样创建一个CustomCursorAdapter的实例......你需要像你现在一样创建光标.
protected String[] from;
protected int[] to;
//From is the column name in your cursor where you're getting the data
//to is the id of the view it will map to
from = new String[]{"name"};
to = new int[]{R.id.textView};
CustomCursorAdapter adapter = new CustomCursorAdapter(this, R.layout.list, cursor, from, to);
listView.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11591 次 |
| 最近记录: |