如何从与GridView关联的Cursor获取数据

时间:2013-04-05 05:40:13

标签: android

我有GridView并使用SimpleCursorAdapter来显示数据库中的数据。 当我点击GridView上的项目时,我想获取与当前元素相关联的数据。我怎么能这样做? 这是我的适配器代码:

public class ReceiptAdapter  extends SimpleCursorAdapter {
private Context context;
private Cursor cursor;
private int layout;
private Map<Object,String> receipt_id_cursor_id=new HashMap<Object,String>();

//public ReceiptAdapter(Context context, ArrayList<Receipt> receiptValues) {
public ReceiptAdapter(Context _context, int _layout, Cursor _cursor, String[]         _from, int[] _to){    
    super(_context, _layout, _cursor, _from, _to);
    cursor = _cursor;
    layout = _layout;
    this.context = _context;
}

@Override
public View newView(Context _context, Cursor _cursor, ViewGroup parent) {
     LayoutInflater inflater = (LayoutInflater) _context.getSystemService(_context.LAYOUT_INFLATER_SERVICE);

     View view  = inflater.inflate(layout, null);
     return view;
}


@Override
public void bindView(View view, Context _context, Cursor _cursor) {

receipt_id_cursor_id.put(_cursor.getPosition(), _cursor.getString(_cursor.getColumnIndex(ReceiptEntry.COLUMN_NAME_RECEIPT_NAME))) ;  

 TextView textView = (TextView) view
            .findViewById(R.id.grid_item_label);
 textView.setText(_cursor.getString(_cursor.getColumnIndex(ReceiptEntry.COLUMN_NAME_RECEIPT_NAME)));
    // set image based on selected text
    ImageView imageView = (ImageView) view
            .findViewById(R.id.grid_item_image);

    imageView.setImageResource(App.getInstance().getResources().getIdentifier(_cursor.getString(_cursor.getColumnIndex(ReceiptEntry.COLUMN_NAME_IC_NAME)) , 
                            "drawable", App.getInstance().getPackageName()));
}


@Override
public int getCount() {
    //return receiptValues.size()-1;
    return cursor.getCount();
}


@Override
public Cursor getItem(int position) {
    //return receiptValues.get(position);
     return this.getCursor();

    //return cursor;
}

@Override
public long getItemId(int position) {
    return cursor.getPosition();
    //return position;
}

当bindView工作时,我看到光标改变它的位置。但是当我按下项目时我不知道用什么方法给我当前的光标位置。例如,在public long getItemId(int position)中,我得到参数“position”,它显示我在网格中的当前位置。

1 个答案:

答案 0 :(得分:0)

public long getItemId(int position)方法中编写以下代码。

cursor.moveToPosition(position);

然后在你的监听器中直接访问你的光标。