How to use CursorAdapter?

2019-08-14 15:28发布

问题:

I am not sure whether the question title is proper or not, but after searching a lot I am asking this.

In my SQLite table, I have the columns

1: _id   2: position   3: path

position: the position of the gridView where the Image is to set
path:  the path of the SDCard having corresponding image

How would I get the image from the path and set into the GridView

GridView grid = (GridView) findViewById(R.id.play_grid_view);
DBAdapter adapter = new DBAdapter(this); //My costum adapter for databse operation
adapter.open();
Cursor cusor = adapter.getAllImages(); //returns cursor with 3 columns mentioned above
startManagingCursor(cusor);

After this what should I do?

回答1:

If your position column means the position of image in grid, you can just sort your query with this column, then cursorAdapter will fill your grid according to positions set in your DB.

This is not usable, if you will skip some of gridview cells (suppose you have following positions in your database: 1,2,4 - then your this adapter will fill positions 1,2,3 as there is actually no position checking)

public class ImageCursorAdapter extends CursorAdapter {
    public ImageCursorAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        String pos = cursor.getString(positionColumnIndex);
        String path = cursor.getString(pathColumnIndex);
        ImageView image = (ImageView)view;
        image.setImageDrawable(Drawable.createFromPath(path));
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View v = new ImageView(context);
        bindView(v, context, cursor);
        return v;
    }
}


回答2:

You are looking for the SimpleCursorAdapter. You need to customize the bindView() method by overriding to show what you want.

You could also try the CursorAdapter itself. Here is a tutorial..