How to retrieve data from a cursor in android?
Solution 1
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.
Solution 2
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.
molleman
Avid rugby player, it student who is doing his final year project at the moment and finding it quite tough! gwt hibernate gilead
Updated on June 26, 2022Comments
-
molleman about 2 years
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? -
Redauser over 8 yearsIn this way won't you always lose the first element of the list? Isn't better to use a do-while cycle instead of a while?
-
Libathos over 6 yearsthat way dont you lose the first item of the cursor?