How to get field value instead of column name?

2019-07-12 14:37发布

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

2条回答
疯言疯语
2楼-- · 2019-07-12 15:30

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.

查看更多
冷血范
3楼-- · 2019-07-12 15:34

Did you try?

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

it will get you the string from the column_name

查看更多
登录 后发表回答