How to get field value instead of column name?

眉间皱痕 提交于 2019-12-24 01:26:07

问题


I want to fill a list with data from a cursor this way:

            myCursor = myDBA.getAllCompanies();
    startManagingCursor(myCursor);

    myListAdapter = new SimpleCursorAdapter(this, R.layout.company_row, myCursor, FROM, TO);

    myListAdapter.setViewBinder(VIEW_BINDER);

    companiesListView.setAdapter(myListAdapter);

I use a custom ViewBinder to fill two TextViews and one ImageView in each row:

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;
    }
};

My problem is the cursor.getString() method call returns the column name not the value of the field and so I get hundreds of rows with column names.

Update:

My getAllCompanies includes a moveToFirst call on the Cursor but still I get column names:

public Cursor getAllCompanies(){
    Cursor s = myDB.query(TABLE, KEYS, WHERE, null, null, null, null);
    s.moveToFirst();
    return s;
}

回答1:


Did you tried to move the cursor to the first index cursor.moveToFirst(); then do cursor.getString(columnIndex); ?

There is another way, create one List or array that will hold the values from the cursor, access all the data inside it by iterating through the cursor

while(cursor.isAfterLast()==false)
{
  list.add(cursor.getString(thestringcollumnindex);
 cursor.moveToNext();
}

then just do

iconName=list.get(columnindex);

This solution is not the best but how ever serves the purpose.




回答2:


Did you try?

 cursor.getString(cursor.getColumnIndex("column_name"));

it will get you the string from the column_name



来源:https://stackoverflow.com/questions/6769820/how-to-get-field-value-instead-of-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!