Search code examples
javaandroiddatabasesqliteandroid-cursor

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?


Solution

  • 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.