[英]Google API - NULL Pointer by getLastKnownLocation
沒錯,我的應用程序運行正常,但是今天早晨它開始崩潰。 我認為觸發因素是我重新啟動了我的智能手機,所以我的APP松開了GPS數據。 我啟動了調試模式,並逐步查找了NULL值,並通過以下命令切實找到了它:
myLocation = locationManager.getLastKnownLocation(provider);
這將返回一個NULL對象,當我嘗試使用以下方法時會導致崩潰:
latitude = myLocation.getLatitude();
longtitude = myLocation.getLongitude();
在這種情況下,如何使我的Location不為NULL? 我嘗試使用NETWORK_PROVIDER,但隨后我必須使用WLAN,這不是我認為的最佳方法。我是否仍可以通過GPS_PROVIDER捕獲信息,而無需進入另一個保存它們的應用程序?
順便說一句,這是我的代碼:
public class gmapps extends FragmentActivity {
private GoogleMap googleMap;
TextView txt_street , txt_city , txt_country ;
Geocoder geocoder;
List<Address> addresses;
ImageView btn_yes;
Location myLocation;
String address , city , country;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
txt_street = (TextView)findViewById(R.id.txt_coordinates);
txt_city = (TextView)findViewById(R.id.txt_city);
txt_country = (TextView)findViewById(R.id.txt_country);
btn_yes = (ImageView)findViewById(R.id.btn_yes);
setUpIfNeeded();
}
private void setUpIfNeeded() {
if (googleMap == null)
{
try{
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}catch(Exception e){}
if (googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap() {
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria , true);
myLocation = locationManager.getLastKnownLocation(provider); // Here I get the NULL
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
double latitude = myLocation.getLatitude();
double longtitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude , longtitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
try {
convert_adresses(latitude,longtitude);
} catch (IOException e) {
e.printStackTrace();
}
txt_street.setText(address);
txt_city.setText(city);
txt_country.setText(country);
}
public void convert_adresses (double lat , double lng) throws IOException
{
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lat, lng, 1);
address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
}
感謝大家 !
您可以像這樣檢查空指針
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Log.d("FlagLocation", "true");
if (provider != null && !provider.equals("")) {
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
double kmInLongitudeDegree = 111.320 * Math.cos(lat / 180.0
* Math.PI);
double deltaLat = RADIUS / 111.1;
double deltaLong = RADIUS / kmInLongitudeDegree;
double minLat = lat - deltaLat;
double maxLat = lat + deltaLat;
double minLong = lng - deltaLong;
double maxLong = lng + deltaLong;
}
只需在getLastLocation()== null時從GPS提供程序中獲取位置。 看看能滿足您需求的android文檔。
http://developer.android.com/training/location/retrieve-current.html
讓我知道您是否需要一些示例代碼,我將編輯答案。 希望這可以幫助。
首先,您應該使用“新的” LocationClent類(為支持LocationServices而已棄用)。
https://developer.android.com/reference/com/google/android/gms/location/LocationClient.html
使用此類getLastLocation()通常可以很好地完成工作,但是正如文檔所述(請參見下文),它有時可能返回null,因此必須進行檢查。
您還應該做的是請求位置更新(請參閱上面的文檔),然后在設備位置可用時,它將在偵聽器上調用onLocationChanged(Location location),然后您可以使用提供的位置。
public Location getLastLocation ()
返回當前可用的最佳最新位置。 如果某個位置不可用(這種情況很少發生),則將返回null。 將返回尊重位置權限的最佳准確性。 此方法提供了一種獲取位置的簡化方法。 它特別適合於不需要精確位置並且不想為位置更新保留額外邏輯的應用程序。
這里是使用位置客戶端的簡化示例。
public class DeviceLocationClient implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private Context context;
private LocationClient locationClient;
private boolean isConnected;
private LocationRequest request;
@Override
public void onLocationChanged(Location location) {
System.out.println("got a location update");
if (location != null ) {
// do something with the location
}
}
public DeviceLocationClient(Context context) {
this.context = context;
System.out.println("connecting to google play services");
locationClient = new LocationClient(context, this, this);
isConnected = false;
locationClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
System.out.println("connection to google play services FAILED!");
}
@Override
public void onConnected(Bundle connectionHint) {
System.out.println("google play servies connected");
isConnected = true;
// locationClient.requestLocationUpdates(request, this);
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
isConnected = true;
requestLLocationUpdates();
}
@Override
public void onDisconnected() {
// TODO Auto-generated method stub
System.out
.println("google play services got disconnected - reconnecting");
mBus.unregister(this);
locationClient.connect();
}
@Subscribe
public void onUpdateLocationRequest(UpdateLocationRequest event) {
System.out.println("got the location request");
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
locationClient.removeLocationUpdates(this);
locationClient.requestLocationUpdates(request, this);
}
public void requestLLocationUpdates() {
System.out.println("requesting location updates updates");
if (isConnected) {
System.out.println("processing request");
System.out.println("sending latest location");
Location lastLocation = locationClient.getLastLocation();
if (lastLocation != null) {
// do something with the last location
}
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
System.out.println("requesting updates");
locationClient.removeLocationUpdates(this);
locationClient.requestLocationUpdates(request, this);
} else {
if (locationClient.isConnecting()) {
System.out.println("google play services is connecting");
} else {
System.out
.println("attempting to connect to google play services");
locationClient.connect();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.