2015-04-05 29 views
2

我有一個位置數據庫。當我嘗試將它們轉換爲座標時,我可以將它們放置在地圖上,從而發現錯誤。我的地址類型地址列表的大小爲零。我研究了這個話題。我所有的清單權限都是正確的。我的手機已連接到互聯網。我重新啓動了手機。我知道有一個谷歌問題,解決方案沒有幫助。地點是準確的。請幫忙。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<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")); 


    } 

EDIT的是這種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; 
} 
+0

請寄出'fetchAllAddresses()'函數。 – 2015-04-05 23:43:26

+0

@DanielNugent我發佈了。 – anu 2015-04-06 00:01:28

回答

0

它看起來就像你沒有在你的光標中得到任何結果一樣,在這種情況下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! 

} 
+1

謝謝。有效。我從一項活動中將數據輸入到數據庫中,並在這一項中提取數據。我不明白爲什麼光標顯示爲空。 @DanielNugent – anu 2015-04-06 00:52:02