Search code examples
androidcursorandroid-cursorloader

Get field from selected CursorLoader


Ive just changed my code to use CursorLoader as opposed to the depreciated manageCursor() methods.

But have no idea how to get fields from the cursor at current clicked position

public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new SQLiteCursorLoader(getActivity(), new DatabaseHelper(getActivity()), "SELECT M.id as _id,  M.name as desc FROM myTable M", null);    
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

        // before I did, 
        // cursor.moveTo(position);
        // cursor.getInt(1);
        // WHat goes here?

Surely I dont have to take the id and requery what the cursor already contains. That would defeat some of the point of this managed concept.

There must be a way to access the fields at a given position.


Solution

  • The proper way of doing this is to use

    l.getItemAtPosition(position);
    

    This is a Cursor, because your adapter is a CursorAdapter (right?), so you can do :

    Cursor cursor = (Cursor) l.getItemAtPosition(position);
    

    and you don't even need to moveToPosition() thing.

    This is equivalent to l.getAdapter().getItem(position), which is a Cursor positioned at position. You could also have a reference to the Adapter and call

    mCursorAdapter.getCursor();