Android:getfromLocationName()在地址列表中返回大小0

我有一个位置数据库。 当我尝试将它们转换为坐标时,我可以将它们放在地图上,我会收到错误。 我的地址类型地址列表的大小为零。 我研究了这个话题。 我的所有清单权限都是正确的。 我的手机已连接到互联网。 我重新启动了手机。 我知道有一个谷歌问题,解决方案没有帮助。 位置准确。 请帮忙。

这是错误消息:android.database.CursorIndexOutOfBoundsException:请求索引0,大小为0

private void setUpMap() { DatabaseHandler db = new DatabaseHandler(this); Cursor c = db.fetchAllAddresses(); String place = c.getString(c.getColumnIndex("name")); Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List 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")); } 

编辑这是fetchAllAddresses()

  public Cursor fetchAllAddresses() { SQLiteDatabase db = this.getWritableDatabase(); Cursor mCursor = db.query(TABLE_CONTACTS, new String[]{ "rowid _id", KEY_NAME,},null, null, null,null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } 

看起来你的光标没有得到任何结果, mCursor.moveToFirst(); 在这种情况下返回false。

通常,您需要检查mCursor.moveToFirst();的结果mCursor.moveToFirst(); ,就好像它返回false一样,你知道你有一个空光标。

空光标是一个单独的问题,很难说这个代码会发生什么。

为了在Cursor为空时摆脱CursorIndexOutOfBoundsException ,这是解决它的一种方法:

您可以检查光标上的getCount()以确保它大于零。 还要确保关闭光标,否则会出现内存泄漏。

 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 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! }