2010-02-08 45 views
2

我想獲得當前很長的經緯度。我對 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);如何解決獲取緯度或GPS空指針異常?

LocationListener myLocationListener = new CurrentLocationListener(); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, myLocationListener); 
    Location currentLocation = locationManager.getLastKnownLocation("gps"); 
    Latitude = currentLocation.getLatitude(); ----->>> null pointer exception here 
    Longitude = currentLocation.getLongitude(); 

public class CurrentLocationListener implements LocationListener{ 
    public void onLocationChanged(Location argLocation) { 
    } 
    public void onProviderDisabled(String provider) { 
    } 
    public void onProviderEnabled(String provider) { 
    } 
    public void onStatusChanged(String provider, int status, Bundle arg2) { 
    } 
} 

得到一個空指針我的清單文件

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 
+0

currentLocation顯然返回空。建議你解決這個問題... – 2010-02-08 07:39:08

+0

其實我是這個領域的新手,請你指導我該怎麼做才能解決這個問題? 是的,它是空.. – UMAR 2010-02-08 07:45:56

+0

你使用模擬器或實際設備? – 2010-02-08 07:58:11

回答

1

你設置清單文件正確的權限?喜歡的東西:

<uses-permission 
    android:name="android.permission.ACCESS_FINE_LOCATION" /> 
1

類明顯...

Location currentLocation = locationManager.getLastKnownLocation("gps"); 

if (currentLocation != null) 
{ 
    Latitude = currentLocation.getLatitude(); 
    Longitude = currentLocation.getLongitude(); 
} 

現在,關於爲什麼的LocationManager返回一個空引用,而不是實際位置參考的...這是很難知道與提供的代碼。可能是任何事情。

編輯:嗯,似乎它可能是你有no gps fix yet

+0

我是否需要安裝別的東西來激活GPS? – UMAR 2010-02-08 08:13:54

+0

從模擬器,運行的時候,去你的DDMS透視圖(這就是所謂的像這樣吧?),選擇「模擬器控制」選項卡,你會看到一個「定位控制」的一部分,你可以發送經/緯度位置 – ccheneson 2010-02-08 13:25:30

3

這通常是因爲沒有最後一個已知位置。要強制獲得可以爲位置更新登記和等待,或者你可以啓動谷歌地圖應用,獲得使用菜單位置的位置 - >我的位置,返回到應用程序,並最後一個已知的位置,不應爲null。

+0

你能不能請填寫這是什麼意思menu->我的位置,以便我可以解決這個問題? – UMAR 2010-02-17 09:17:41

+0

(觸摸)谷歌地圖應用程序(圖標) - >(按)菜單(按鈕) - >(觸摸)我的位置(圖標) – 2010-02-17 16:54:55

+0

thanks..it工作.. – 2014-10-10 06:43:53