【问题标题】:Android: getfromLocationName() returns size 0 in Address ListAndroid:getfromLocationName() 在地址列表中返回大小 0
【发布时间】:2015-04-05 22:58:05
【问题描述】:

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

这是错误信息: 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<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"));


    }

编辑这是 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;
}

【问题讨论】:

  • 请发fetchAllAddresses()函数。
  • @DanielNugent 我发布了。

标签: java android dictionary location geocoding


【解决方案1】:

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

通常你会想要检查mCursor.moveToFirst(); 的结果,如果它返回false,你就知道你有一个空游标。

空光标是一个单独的问题,很难从这段代码中看出为什么会发生这种情况。

为了在光标为空时摆脱您的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<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!

 }

【讨论】:

  • 谢谢。有效。我已经从一项活动中将值输入到我的数据库中,并在这项活动中获取它们。我不明白为什么光标显示为空。 @DanielNugent
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 2020-03-31
  • 1970-01-01
  • 2012-09-08
  • 2020-12-16
  • 2021-08-14
  • 1970-01-01
相关资源
最近更新 更多