2012-03-16 56 views
0

我目前使用游标检索整个数据库检索排前三的是Android数据库的内容 我的代码是在我的代码使用游标

public Cursor getAll() { 
    return (getReadableDatabase().rawQuery(
      "SELECT _id, note, amt, dueDate FROM New", null)); 

} 

的检索内容的功能在listview中填充它们。

现在我想要使用光标检索相同数据库的前三行的内容以显示在另一个列表视图中。

需要帮助,在此先感谢。

回答

0

这样做是对的结果数量限制在3到正确的方法:

"SELECT _id, note, amt, dueDate FROM New ORDER BY _id LIMIT 3" 

然后你只需遍历光标(像往常一样)

+0

其工作伴侣。谢谢 – user1166422 2012-03-16 10:54:35

+0

很高兴我可以帮助:) – MByD 2012-03-16 10:55:08

0

既然你已经获得了Cursor,为了得到结果的前三排,你这样做:

Cursor cursor = getAll(); 
cursor.moveToFirst(); 
int count = 0; 
while(!cursor.isAfterLast() && count < 3) 
{ 
    // Grab your data here using cursor.getLong(0), cursor.getString(1) etc. 
    // and store it an array. 
    count++; 
    cursor.moveToNext(); 
} 
cursor.close(); 

您可能希望通过增加一个LIMIT 0,3限制查询结果最多三个声明到您的SQL。获得了包含您的记录的最多三个元素的数组后,您可以继续将它们放在您所指的其他ListView中。您可以通过将它们添加到此ListView的源数组中来完成此操作。然后调用ListView适配器的notifyDataSetChanged方法使其自行更新。

+0

其工作,谢谢队友 – user1166422 2012-03-16 11:05:19

0

所以你可以通过两种方式做到这一点:

  1. 创建一个单独的选择:

    SELECT * FROM Table_Name LIMIT 3; 
    
  2. 选择从光标三行:

    int n = 0; 
    cursor.moveToFirst(); 
    while (!cur.isAfterLast() && n < 3) { 
        // Use the data 
        n++; 
        cur.moveToNext(); 
    } 
    cur.close(); 
    
+0

谢谢大家。解决了这个问题,并理解了一些方法来做到这一点。 – user1166422 2012-03-16 11:03:14