Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));

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?

like image 762
molleman Avatar asked Dec 10 '22 07:12

molleman


2 Answers

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.

like image 180
Flo Avatar answered Dec 14 '22 22:12

Flo


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.

like image 42
DArkO Avatar answered Dec 14 '22 22:12

DArkO