2014-03-03 43 views
2

我不认为我一直这样做是正确的。一个好友告诉我使用cursor.getColumnIndex()来检索该表列中项目的值。在我看来,它只是返回表格中列的位置的int值,这就是为什么当我执行下面的代码时,我得到了2.0或3.0的我的经纬度值,因为它们是第二和第三列桌子。使用光标检索SQLite db

什么是这种方法返回在长长的列中的项目,而不是他们在表中的位置正确的方法是什么?

下面是我用用getColumnIndex()什么:

public List<LatLng> getAllPositions() { 
    List<LatLng> positionList = new ArrayList<LatLng>(); 
     SQLiteDatabase database; 
     ResumeMySQLiteHelper dbHelper; 

     dbHelper = new ResumeMySQLiteHelper(this); 
    database = dbHelper.getWritableDatabase(); 

    String[] allColumns = { ResumeMySQLiteHelper.COLUMN_ID, 
       ResumeMySQLiteHelper.COLUMN_COMMENT, ResumeMySQLiteHelper.COLUMN_LAT, ResumeMySQLiteHelper.COLUMN_LONG }; 

    Cursor cursor = database.query(ResumeMySQLiteHelper.TABLE_NAME, 
     allColumns, null, null, null, null, null); 

    cursor.moveToFirst(); 
    while (!cursor.isAfterLast()) { 


     double latitude = cursor.getColumnIndex("lat"); 
     double longitude = cursor.getColumnIndex("long"); 
     String testString = Double.toString(latitude); 
     String testLong = Double.toString(longitude); 
     Log.w("myApp", testString + " " + testLong); 

     //currently prints myApp 2.0 3.0 for every row in table 

     LatLng newLatLng = new LatLng(latitude, longitude); 
     positionList.add(newLatLng); 
     cursor.moveToNext(); 
    } 
    // make sure to close the cursor 
    cursor.close(); 
    return positionList; 
    } 

回答

4

此:

double latitude = cursor.getColumnIndex("lat"); 

应该是:

double latitude = cursor.getDouble(cursor.getColumnIndex("lat")); 

和双经度

相同
+2

是的,你得到那一个:D – MDMalik

+1

我刚才读了几分钟之前你的问题。或者你会回答相同的问题。 ;) –

+2

@ArtooDetoo很好很棒! +1 up –

1

int cloumnIndex = cursor.getColumnIndex("lat"); 为找到保存“lat”值 的列的索引,找到该列的索引后需要查找值。

cursor.getDouble(columnIndex);