Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite how to get string items using cursor

public Cursor getImages(long rowId) throws SQLException
{
    Cursor mCursor =
            db.rawQuery("select * from Pictures WHERE id=" + rowId + ";", null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

Table columns "id, pic, comment"

I want to take values of pic & comment to string array.

My code is:

int i=0;
Cursor c1 = db.getImages(memberId);     
c1.moveToFirst();
while(c1.isLast()){
    pictures[i]=c1.getString(1);
    comments[i]=c1.getString(2);
    i++;
}

this not working.

like image 726
Saruulbat Avatar asked Apr 26 '12 08:04

Saruulbat


People also ask

Which method is used to get data from cursor?

Once the cursor's position is pointing to a valid row, the columns of the row can be read from the cursor. To read the data, the code in Listing 5.10 uses two methods from the cursor class: Cursor. getColumnIndexOrThrow() and one of the type get() methods from the Cursor class.

What is cursor moveToFirst ()?

moveToFirst() method moves the cursor to the first row.

What is cursor in SQLite?

The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory.

Which function do you call from a cursor object to get the number of rows in the cursor object?

Execute the SELECT query using the cursor. execute() method. Get resultSet (all rows) from the cursor object using a cursor. fetchall() .


2 Answers

You should do it like this:

c1.getString(cursor.getColumnIndex("pic"));

and

c1.getString(cursor.getColumnIndex("comment"));

like image 68
zionpi Avatar answered Sep 30 '22 10:09

zionpi


This is the way I do it

I prefer

getColumnIndex()

instead of number.

if(cursor.moveToFirst()){
    do{
          String varaible1 = cursor.getString(cursor.getColumnIndex("column_name1"));
          String varaible2 = cursor.getString(cursor.getColumnIndex("column_name2"));

       }while (cursor.moveToNext());
}
cursor.close();

Always use column name instead of position, because column position can change.

of course column name can change as well but let say if you add a new column and it position between column 1 and column 2. You need to change your code if you use number. But if you use name, you will be fine.

and it is more readable and what happened if you have 40 columns?(<-some say, it is bad)

like image 36
NOT_A_PROGRAMMER Avatar answered Sep 30 '22 10:09

NOT_A_PROGRAMMER