I have a database of locations. When I try to convert them into coordinates so I can place them on a map I get errors. My addresslist of type address has a size zero. I research
It looks like you're not getting any results in your cursor, and mCursor.moveToFirst();
is returning false in this case.
Typically you would want to check the result of mCursor.moveToFirst();
, as if it returns false, you know that you have an empty cursor.
The empty cursor is a separate issue, it's hard to tell why that would happen from this code.
In order to get rid of your CursorIndexOutOfBoundsException
when the Cursor is empty, this is one way to fix it:
You can do a check to getCount()
on your cursor to make sure it's greater than zero.
Also make sure to close the cursor, otherwise you will have a memory leak.
private void setUpMap() {
DatabaseHandler db = new DatabaseHandler(this);
Cursor c = db.fetchAllAddresses();
//check for empty cursor
if (c.getCount() > 0){
String place = c.getString(c.getColumnIndex("name"));
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<android.location.Address> addresses = new ArrayList();
try {
addresses = geocoder.getFromLocationName(place,1);
} catch (IOException e) {
e.printStackTrace();
}
android.location.Address add = addresses.get(0);
double lat = add.getLatitude();
double lng = add.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title("Marker"));
}
c.close(); //get rid of memory leak!
}