如何在Android中将数据库值获取到一个字符串数组中(SQLite数据库)

7

我有一个名为“CUED”的数据库(SQLite Android),它有一个名为HELLO的表,其中包含一个NAME列。我可以从该列获取字符串的值。 让我展示一下我的代码片段:

myDB =hello.this.openOrCreateDatabase("CUED", MODE_PRIVATE, null); 
Cursor crs = myDB.rawQuery("SELECT * FROM HELLO", null);
                
while(crs.moveToNext())
{
    String uname = crs.getString(crs.getColumnIndex("NAME"));
    System.out.println(uname);
}

它将逐个打印出值。现在我需要的是,我想从数据库中获取列值,以便我可以将其存储在字符串数组中。

3个回答

25

你已经完成了难点... 数组部分相当简单:

String[] array = new String[crs.getCount()];
int i = 0;
while(crs.moveToNext()){
    String uname = crs.getString(crs.getColumnIndex("NAME"));
    array[i] = uname;
    i++;
}

无论如何,我始终建议在这种情况下使用集合:

List<String> array = new ArrayList<String>();
while(crs.moveToNext()){
    String uname = crs.getString(crs.getColumnIndex("NAME"));
    array.add(uname);
}

为了比较数组,您可以这样做:

boolean same = true;
for(int i = 0; i < array.length; i++){
    if(!array[i].equals(ha[i])){
        same = false;
        break;
    }
}
// same will be false if the arrays do not have the same elements

谢谢兄弟,现在能再帮我一次吗?我有另一个字符串数组,我想比较数组中的值。让我解释一下我的第一个数组——String[] ha={"hello","hai"}; 和来自数据库的 String 数组——String[] array={"hello","hai"}; 我想检查两个数组的每个位置是否相同,如果都相同,就让我进入下一页。 - Ramz
好的,但是如果需要从一行中获取所有列的值以形成字符串数组,该怎么做? - Subha
嘿,非常好的答案... 如果返回多行该怎么办? String uname = crs.getString(crs.getColumnIndex("NAME")); String lname = crs.getString(crs.getColumnIndex("LASTNAME")); - Tushar Narang
1
不要忘记crs.close(); - PhilipB

0
       String[] str= new String[crs.getCount()];
       crs.movetoFirst();           
     for(int i=0;i<str.length();i++)
        { 
           str[i] = crs.getString(crs.getColumnIndex("NAME"));
            System.out.println(uname);
      crs.movetoNext();
        }

尽情享受吧


您没有移动光标位置。 - Cristian

0

这是我的代码,它返回一个包含字段值的ArrayList:

public ArrayList<String> getAllPlayers() {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cur = db.rawQuery("SELECT " + serailnumber + " as _id, " + title
            + " from " + table, new String[] {});
    ArrayList<String> array = new ArrayList<String>();
    while (cur.moveToNext()) {
        String uname = cur.getString(cur.getColumnIndex(title));
        array.add(uname);

    }
    return array;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接