Sqlite how to get string items using cursor
Asked Answered
A

5

7
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.

Aseptic answered 26/4, 2012 at 8:10 Comment(0)
D
14

You should do it like this:

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

and

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

Definiendum answered 26/4, 2012 at 8:21 Comment(0)
B
5

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)

Bittencourt answered 10/2, 2016 at 21:10 Comment(2)
Always use column name instead of position, because column position can change. Are there any differences in performance between the two?Phraseologist
@Phraseologist I believe position is fasterBittencourt
R
4

simply use moveToNext in your loop to iterate.

while(ct.moveToNext()){
     pictures[i]=c1.getString(1);
     comments[i]=c1.getString(2);
     i++;
}
Romanfleuve answered 26/4, 2012 at 8:29 Comment(0)
E
2

And what you should do is to replace

c1.moveToFirst();
while(c1.isLast()){
     //your code
}

By

//c1.moveToFirst();
while(c1.moveToNext()){
     //your code
}
Evanne answered 26/4, 2012 at 8:28 Comment(0)
W
1
Cursor c = db.rawQuery("select username from user_information where username ='" + username_txt.getText() + "'", null);
c.moveToFirst();
if (c.moveToFirst()) {
    username = c.getString(c.getColumnIndex("username"));
}

Use this. I hope it helps you.

Wehrle answered 10/3, 2015 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.