Android: getfromLocationName() returns size 0 in Address List

后端 未结 1 1724
庸人自扰
庸人自扰 2021-01-22 01:15

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

相关标签:
1条回答
  • 2021-01-22 01:43

    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!
    
     }
    
    0 讨论(0)
提交回复
热议问题