开发者

How to retrieve data from a cursor in android?

I retrieve information from my database and it is all in a Cursor. Now i need to go through each item in the cursor to retrieve lng lats and a name to display on a map.

Cursor c = mDbHelper.fetchSpot(15);
        startManagingCursor(c);

        double lat = Double.parseDouble(c.getString(c.getColumnIndexOrThrow(ParkingSpotDBAdapter.KEY_LAT)));
        double lng = Double.parseDouble(c.getString(c.getColumnIndexOrThrow(ParkingSpotDBAdapter.KEY_LNG)));
        String name = c.getString(c.getColumnIndexOrThrow(ParkingSpotDBAdapter.KEY_ADDRESS));
开发者_Go百科

I Have antoher method called fecthAllSpots() this returns many items in the cursor, how do i go about retrieving each lng lat and name from each row in that cursor?


You can use a while loop to iterate of all row the cursor returns.

while(c.moveToNext()){
    double lat = Double.parseDouble(c.getString(c.getColumnIndexOrThrow(ParkingSpotDBAdapter.KEY_LAT)));
    double lng = Double.parseDouble(c.getString(c.getColumnIndexOrThrow(ParkingSpotDBAdapter.KEY_LNG)));
    String name = c.getString(c.getColumnIndexOrThrow(ParkingSpotDBAdapter.KEY_ADDRESS));
}

Of course you have to do something with the lat, lng and name variable as they will get overridden on each iteration. I suggest you implement a DBLocation class which can store the name, longitude and latitude of a location. You can then store all the objects you create from the cursor in a array or list.


First. you can just use the getInt, getLong etc.. methods on teh cursor to retrieve the values instead of parsing them afterwards.

The question:

here is the sintax:

first query the db to get a cursor.

next do a null check on the cursor (just in case because it sometimes happens), doable with try catch block also.

next write:

    if(c.moveToFirst()){
do{
// YOUR CODE FOR EACH CURSOR ITEM HERE.
// the cursor moves one field at a time trhough it's whole dataset
}while(c.moveToNext())
}

at the end close the cursor or if it is a managed query do nothing the activity will close it for you. REmember all this in a block and apart for everything else you will be checking consider a nullPointerException for the cursor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜