Android Sqlite 如何使用游标获取字符串项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10329500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sqlite how to get string items using cursor
提问by Saruulbat
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"
表格列“id、pic、comment”
I want to take values of pic & comment to string array.
我想将 pic 和 comment 的值带到字符串数组中。
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.
这不起作用。
回答by zionpi
You should do it like this:
你应该这样做:
c1.getString(cursor.getColumnIndex("pic"));
c1.getString(cursor.getColumnIndex("pic"));
and
和
c1.getString(cursor.getColumnIndex("comment"));
c1.getString(cursor.getColumnIndex("comment"));
回答by NOT_A_PROGRAMMER
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.
当然列名也可以更改,但假设您添加一个新列并且它位于第 1 列和第 2 列之间。如果使用数字,则需要更改代码。但是如果你使用name,你会没事的。
and it is more readable and what happened if you have 40 columns?(<-some say, it is bad)
它更具可读性,如果您有 40 列会发生什么?(<-有人说,这很糟糕)
回答by waqaslam
simply use moveToNext
in your loop to iterate.
只需moveToNext
在循环中使用即可进行迭代。
while(ct.moveToNext()){
pictures[i]=c1.getString(1);
comments[i]=c1.getString(2);
i++;
}
回答by Alexandre B.
And what you should do is to replace
而你应该做的是更换
c1.moveToFirst();
while(c1.isLast()){
//your code
}
By
经过
//c1.moveToFirst();
while(c1.moveToNext()){
//your code
}
回答by Alexandre B.
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.
用这个。我希望它能帮助你。