Android 如何获取字段值而不是列名?
我想用光标的数据填充列表,如下所示:Android 如何获取字段值而不是列名?,android,cursor,android-viewbinder,Android,Cursor,Android Viewbinder,我想用光标的数据填充列表,如下所示: myCursor = myDBA.getAllCompanies(); startManagingCursor(myCursor); myListAdapter = new SimpleCursorAdapter(this, R.layout.company_row, myCursor, FROM, TO); myListAdapter.setViewBinder(VIEW_BINDER); co
myCursor = myDBA.getAllCompanies();
startManagingCursor(myCursor);
myListAdapter = new SimpleCursorAdapter(this, R.layout.company_row, myCursor, FROM, TO);
myListAdapter.setViewBinder(VIEW_BINDER);
companiesListView.setAdapter(myListAdapter);
我使用自定义的ViewBinder
在每行填充两个textview
和一个ImageView
:
private final ViewBinder VIEW_BINDER = new ViewBinder() {
/**
* Binds the Cursor column defined by the specified index to the
* specified view.
*/
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
int viewId = view.getId();
switch (viewId) {
case R.id.company_name:
case R.id.company_desc:
Log.d(TAG, "Binding TextView");
TextView venueText = (TextView) view;
venueText.setText(cursor.getString(columnIndex));
return true;
case R.id.company_icon:
Log.d(TAG, "Binding ImageView");
ImageView venueIcon = (ImageView) view;
String iconName;
iconName = cursor.getString(columnIndex); //Here I get the column name not the field value
Resources resources = myContext.getResources();
Drawable drawable = resources.getDrawable(resources
.getIdentifier("my.package:drawable/"
+ iconName, null, null));
venueIcon.setImageDrawable(drawable);
return true;
}
return false;
}
};
我的问题是cursor.getString()
方法调用返回的是列名而不是字段的值,因此我得到了数百行列名
更新:
我的getAllCompany
s在光标上包含了一个moveToFirst
调用,但我仍然得到了列名:
public Cursor getAllCompanies(){
Cursor s = myDB.query(TABLE, KEYS, WHERE, null, null, null, null);
s.moveToFirst();
return s;
}
是否尝试将光标移动到第一个索引cursor.moveToFirst()代码>然后执行cursor.getString(columnIndex)代码>
还有另一种方法,创建一个列表或数组来保存游标中的值,通过遍历游标访问其中的所有数据
while(cursor.isAfterLast()==false)
{
list.add(cursor.getString(thestringcollumnindex);
cursor.moveToNext();
}
那就做吧
iconName=list.get(columnindex);
此解决方案不是最好的,但如何达到此目的。您尝试过吗
cursor.getString(cursor.getColumnIndex("column_name"));
它将从列名称中获取字符串,我将在myDBA.getallcompanys()中调用moveToFirst
代码>你应该没问题。他将在哪里调用moveToFirst并不重要,只要是在他从中获取数据之前,对吗?没错:不过,将其隐藏在返回光标的函数中是最容易的。如果它返回一个光标
,它就可以开始了:无需进一步摸索。如果moveToFirst
失败,则返回null并跳过整个练习。谢谢。事实上,我尝试了moveToFirst
,但仍然得到了列名。我将尝试使用数组。