游标while循环返回每个值但最后一个

jcr*_*son 6 java sql sqlite android cursor

我使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

从此我得到:


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组值,我应该得到8组.

谢谢.

Par*_*ker 22

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());
}
Run Code Online (Sandbox Code Playgroud)

  • 你可能想要一些东西,以确保有一个第一个元素,如果它最终在一个空元素可能不会太好. (5认同)
  • 确保你使用try catch. (2认同)

Pen*_*m10 5

Cursor c=null;
c=......;
try {
    if (c!=null) {
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

        }

    }
} finally {
    if (c!=null) {
        c.close();
    }
}
Run Code Online (Sandbox Code Playgroud)