ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-11 14:30:33  阅读:207  来源: 互联网

标签:android java dictionary location geocoding


我有一个位置数据库.当我尝试将其转换为坐标时,将其放置在地图上时会出错.我的地址类型地址列表的大小为零.我研究了这个话题.我所有的清单权限均正确.我的手机已连接到互联网.我已经重启了手机.我知道有一个Google问题,解决方案也无济于事.位置准确.请帮忙.

这是错误消息:
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;
}

解决方法:

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

通常,您将需要检查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<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!

 }

标签:android,java,dictionary,location,geocoding
来源: https://codeday.me/bug/20191011/1893260.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有