2011-08-01 51 views
0

我試圖在單擊按鈕時獲取用戶的位置。
我在我的按鈕下面的代碼的onclick監聽器:
位置管理器android問題

 

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
Criteria criteria = new Criteria(); 
bestProvider = locationManager.getBestProvider(criteria, false); 
Location currentLocation = locationManager.getLastKnownLocation(bestProvider); 
Log.e(tag,"reached till here"); 
location = Double.toString(currentLocation.getLatitude()) + " " + Double.toString(currentLocation.getLongitude()); 
Toast.makeText(getApplicationContext(), location, Toast.LENGTH_LONG); 
MyLocation.setText(location); 
 

我收到的輸出reached till here在logcat中。之後,應用程序停止並要求我強制關閉它。我最初做了一些搜索,發現getLatitude和getLongitude返回double值。所以我糾正了代碼。但我仍然遇到錯誤。我究竟做錯了什麼?

編輯:的logcat的錯誤:
得到的RemoteException發送SETACTIVE(假)通知爲PID 796 UID 10036
我覺得currentLocation是返回null

+0

可以調試,看看你的對象「currentLocation」爲空?還有,你在logcat中得到的錯誤是什麼? – Finuka

+0

發佈logcat以查找它崩潰的原因。 – PravinCG

+0

請給我們看日誌。這可能是因爲沒有最後的已知位置。然後你會得到null。 – TofferJ

回答

3

如果您是在Emulator你可能測試您的應用程序沒有任何提供商,並且currentLocation對象爲空,這就是爲什麼getLatitude()getLongitude()將提供NPE。

編輯:正如@grinnner所說,從DDMS的角度來看,你可以模擬發送位置座標。在eclipse中打開DDMS透視圖,在LocationControls選項卡中設置經度和緯度,然後單擊發送。確保設備選項卡中的焦點位於您正在運行應用程序的模擬器上。

+0

如果他使用Eclipse,他可以從DDMS角度欺騙位置。 – thegrinner

+0

如果我使用模擬器,你能告訴我如何獲得提供者嗎? – Brahadeesh

+0

@thegrinner我不知道該怎麼做。你能解釋一下這些步驟嗎? – Brahadeesh

1

如果您沒有最後一個已知位置(只對返回的值做一個簡單的空檢查),那麼您需要添加位置偵聽器來獲取位置。事情是這樣的:

// Start listening for a new location. 
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
String bestProvider = lm.getBestProvider(new Criteria(), true);  
mMyLocationListener = new MyLocationListener(); 
lm.requestLocationUpdates(bestProvider, 0, 0, mMyLocationListener); 

private class MyLocationListener implements LocationListener { 

    @Override 
    public void onLocationChanged(Location location) { 
     // Do what you need to do with the longitude and latitude here. 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 
} 

你還應該記住刪除位置監聽器,只要你不再需要它:

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
lm.removeUpdates(mMyLocationListener); 
mMyLocationListener = null; 
+0

我不想位置更新。我只是想找到一次的位置。我有一個實現位置監聽器的類中的代碼。 – Brahadeesh

+0

即使你只想要一次的位置,我認爲這是獲得它的唯一方法,如果你沒有最後一個已知的位置。註冊一個監聽器,一旦你得到一個更新,刪除該監聽器並使用你得到的位置。但是,如果問題在於模擬器沒有提供給您,請參閱Ovidiu的答案。 :) – TofferJ

+0

是的。請檢查我的最後評論他的答案。儘管謝謝你的回答。 – Brahadeesh