6

我正在使用 while 循环遍历游标,然后输出数据库中每个点的经度和纬度值。

由于某种原因,它没有返回游标中的最后一个(或第一个取决于我是否使用 Cursor.MoveToLast)经度和纬度值集。

这是我的代码:

public void loadTrack() {
SQLiteDatabase db1 = waypoints.getWritableDatabase();
Cursor trackCursor = db1.query(TABLE_NAME, FROM, "trackidfk=1", null, null, null,ORDER_BY); 

    trackCursor.moveToFirst();
    while (trackCursor.moveToNext()) {
        Double lat = trackCursor.getDouble(2);
        Double lon = trackCursor.getDouble(1);
        //overlay.addGeoPoint( new GeoPoint( (int)(lat*1E6),  (int)(lon*1E6)));
        System.out.println(lon);
        System.out.println(lat);
    }
}

从这里我得到:

*******************************************
04-02 15:39:07.416: INFO/System.out(10551): 3.0
04-02 15:39:07.416: INFO/System.out(10551): 5.0
04-02 15:39:07.416: INFO/System.out(10551): 4.0
04-02 15:39:07.416: INFO/System.out(10551): 5.0
04-02 15:39:07.416: INFO/System.out(10551): 5.0
04-02 15:39:07.416: INFO/System.out(10551): 5.0
04-02 15:39:07.416: INFO/System.out(10551): 4.0
04-02 15:39:07.416: INFO/System.out(10551): 4.0
04-02 15:39:07.416: INFO/System.out(10551): 3.0
04-02 15:39:07.416: INFO/System.out(10551): 3.0
04-02 15:39:07.416: INFO/System.out(10551): 2.0
04-02 15:39:07.416: INFO/System.out(10551): 2.0
04-02 15:39:07.493: INFO/System.out(10551): 1.0
04-02 15:39:07.493: INFO/System.out(10551): 1.0
***************************************************************
7 Sets of values, where I should be getting 8 sets.

谢谢。

4

4 回答 4

23

moveToNext() 有两个特点。它返回一个布尔值,表示有一个,但同时它继续前进并移动光标。

public void loadTrack() {
SQLiteDatabase db1 = waypoints.getWritableDatabase();
Cursor trackCursor = db1.query(TABLE_NAME, FROM, "trackidfk=1", null, null, null,ORDER_BY); 

    trackCursor.moveToFirst();
    do {
        Double lat = trackCursor.getDouble(2);
        Double lon = trackCursor.getDouble(1);
        //overlay.addGeoPoint( new GeoPoint( (int)(lat*1E6),  (int)(lon*1E6)));
        System.out.println(lon);
        System.out.println(lat);
    } while (trackCursor.moveToNext());
}
于 2010-04-02T16:40:17.970 回答
5
Cursor c=null;
c=......;
try {
    if (c!=null) {
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

        }

    }
} finally {
    if (c!=null) {
        c.close();
    }
}
于 2010-04-02T16:29:12.423 回答
4

您实际上跳过了第一个值,而不是最后一个。

trackCursor.moveToFirst();
while (trackCursor.moveToNext()) {

第一次进入 while 循环时,您指向的是第二行。

我会将您的while 循环转换为 do-while 循环

于 2010-04-02T15:54:27.367 回答
3

您刚刚执行了查询。你不能摆脱 moveToFirst() 吗?

public void loadTrack() {
SQLiteDatabase db1 = waypoints.getWritableDatabase();
Cursor trackCursor = db1.query(TABLE_NAME, FROM, "trackidfk=1", null, null, null,ORDER_BY); 

    while (trackCursor.moveToNext()) {
        Double lat = trackCursor.getDouble(2);
        Double lon = trackCursor.getDouble(1);
        //overlay.addGeoPoint( new GeoPoint( (int)(lat*1E6),  (int)(lon*1E6)));
        System.out.println(lon);
        System.out.println(lat);
    }
}
于 2010-04-03T00:26:42.780 回答