gpt4 book ai didi

java - Android:java.lang.NullPointerException:尝试调用虚拟方法'double android.location.Location.getLatitude()

转载 作者:行者123 更新时间:2023-12-02 12:13:41 25 4
gpt4 key购买 nike

我正在 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);

}

最佳答案

您正在获取位置的空对象,因此在访问纬度和日志之前进行空点检查

if(location!= null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();}

关于java - Android:java.lang.NullPointerException:尝试调用虚拟方法'double android.location.Location.getLatitude(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46357116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com