【问题标题】:How to get field value instead of column name?如何获取字段值而不是列名?
【发布时间】:2011-10-09 20:01:30
【问题描述】:

我想以这种方式用光标中的数据填充列表:

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

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

    myListAdapter.setViewBinder(VIEW_BINDER);

    companiesListView.setAdapter(myListAdapter);

我使用自定义ViewBinder 在每行中填充两个TextViews 和一个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() 方法调用返回的是列名而不是字段的值,所以我得到了数百行带有列名的行。

更新:

我的getAllCompanies 包括对CursormoveToFirst 调用,但我仍然得到列名:

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

【问题讨论】:

    标签: android cursor android-viewbinder


    【解决方案1】:

    您是否尝试将光标移动到第一个索引cursor.moveToFirst(); 然后执行cursor.getString(columnIndex);

    还有另一种方法,创建一个列表或数组来保存游标中的值,通过遍历游标来访问其中的所有数据

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

    那就做吧

    iconName=list.get(columnindex);
    

    这个解决方案不是最好的,但无论如何都可以达到目的。

    【讨论】:

    • 我会支持这个:在myDBA.getAllCompanies(); 中调用moveToFirst,你应该会没事的。
    • 他在哪里调用 moveToFirst 并不重要,只要是在他从中获取数据之前,对吧?
    • 没错:不过最简单的方法是把它埋在返回Cursor 的函数中。如果它返回一个Cursor,它就可以开始了:不需要进一步摸索。如果moveToFirst 失败,则返回 null 并跳过整个练习。
    • 谢谢。事实上,我尝试使用moveToFirst,但我仍然得到列名。我会尝试使用数组。
    【解决方案2】:

    你试过了吗?

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

    它会从 column_name 中获取字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2020-02-25
      相关资源
      最近更新 更多