我正在android中创建一个方向性应用程序。为什么我必须从Android设备获取位置这里是我的代码当我运行此代码它给我这些行的例外
curlat = location.getLatitude();
curlng = location.getLongitude();
这是整个功能
public void newlocation(Context context) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
// user defines the criteria
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
mylistener = new MyLocationListener();
if (location != null) {
mylistener.onLocationChanged(location);
} else {
// leads to the settings because there is no last known location
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// location updates: at least 1 meter and 200millsecs change
locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
// String a=""+location.getLatitude();
// Toast.makeText(getApplicationContext(), a, 222).show();
curlat = location.getLatitude();
curlng = location.getLongitude();
Log.d("************", "1111111111111111");
new GetAddressTask(this).execute(location);
}
答案 0 :(得分:1)
您正在获取位置的null对象,因此在访问lat和log之前进行空点检查
if(location!= null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();}