Search code examples
androidstringandroid-sqliteandroid-cursor

Pulling information from one row cursor - Android SQLite


I have this issue where I am trying to fill a String[] with stuff, but the way I am doing it is not working. My app so far, takes XML data, parses it, shoves it into a separate tables, and displays the Items in a list. I'm working on the detailed view, and this is where I am stuck. I keep getting a nullpointer exception error because, even though the String[] has the correct number of 'slots' (I've checked this) they are null.

This is the function:

public String[] getDetails(String id, int param){

    Cursor cursor = getDetailsCursor(id, param);

    String[] details = new String[cursor.getColumnCount()];
    int itty=0;

    if (cursor.moveToFirst()){
           do{
              details[itty] = cursor.getString(itty);

              itty++;
           }while(cursor.moveToPosition(itty));
        }
        cursor.close();

    return details;

}

Before we ask: It is the right cursor, from information that sometimes come through and the ColumnCount, I know it is the right cursor.

I've ask you guys questions before and you seem to know what it is pretty much instantly. This would probably be the last question I have for this little project.

Update

    public String[] getDetails(String id, int param){

    Cursor cursor = getDetailsCursor(id, param);

    String[] details = new String[cursor.getColumnCount()] , names = new String[cursor.getColumnCount()];

    int i=0;

    cursor.moveToFirst();

    names = cursor.getColumnNames();

    cursor.moveToFirst();

    for(i=0;i < names.length;i++){
        details[i] = cursor.getString(cursor.getColumnIndex(names[i]));
    }

        cursor.close();

    return details;

}

This is the code I currently have. I am going to try your solutions and see if they have the same result.


Solution

  • The Cursor methods moveTo... move the row you're dealing with and not the column. Passing an int to a call on getString(...) defines the column number. You basically need to do something like this...

    if (cursor.moveToFirst()) {
        for (int itty = 0; itty < cursor.getColumnCount(); itty++) {
            details[itty] = cursor.getString(itty);
        }
    }