安卓地理位置开发,报错:Attempt to invoke virtual method ‘double android.location.Location.getLatitude()’ on a null object reference
这两天在做一个简单地通过手机获取经纬度并上传至服务器,在这个过程中遇到问题:
先放一下我的代码:
private void initLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providerList = locationManager.getProviders(true);
if (providerList.contains(LocationManager.GPS_PROVIDER)) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
Log.i("Locator","含有GPS定位");
}
else {
Log.i("Locator","不含GPS定位");
}
latitude = location.getLatitude();
longitude = location.getLongitude();
}
运行后就报了上面那个错。先分析一下这个错误,大概意思是说没有location这个对象,但是我却调用了这个方法。
这说明getLastKnownLocation这个方法是有可能返回一个为null的location。
解决方法当然就是给其加上一个判断location是否为null。改后的程序如下:
private void initLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providerList = locationManager.getProviders(true);
if (providerList.contains(LocationManager.GPS_PROVIDER)) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
Log.i("Locator","含有GPS定位");
}
else {
Log.i("Locator","不含GPS定位");
}
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
else{
Log.i("Locator","location为空");
}
}
作为小白的我很奇怪,按理来说这个函数只在我的程序中执行了一次,若location为null的话longitude和latitude是不会被赋值的,但是最后的结果是程序跑出了正确的longitude和latitude。
总之这样改是正确的,待我想明白这个问题再来写写。