我正在使用谷歌地图活动,当我写出乱码并点击“搜索”时,应用程序就会崩溃。但是,它与真实位置完美配合。如何防止它崩溃?
我的代码:
public void onSearch(View view) {
String location = locationTS.getText().toString();
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
List<Address> addressList=null;
try {
addressList= geocoder.getFromLocationName(location, 1);
mMap.clear();
} catch (IOException e) {
e.printStackTrace();
}
Address address=addressList.get(0);
LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,80));
latitudeB=latLng.latitude;
longitudeB=latLng.longitude;
}
else {
Toast.makeText(getApplicationContext(), "please fill in an available location",
Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
在代码中获取纬度和经度之前添加此检查
address.hasLatitude() && address.hasLongitude()
试试这个
public void onSearch(View view) {
String location = locationTS.getText().toString();
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
List<Address> addressList=null;
try {
addressList= geocoder.getFromLocationName(location, 1);
mMap.clear();
Address address=addressList.get(0);
// check if it has lat and long
if(address.hasLatitude() && address.hasLongitude()){
LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,80));
latitudeB=latLng.latitude;
longitudeB=latLng.longitude;
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(getApplicationContext(), "please fill in an available location",
Toast.LENGTH_LONG).show();
}
}
答案 1 :(得分:0)
来自Geocoder.getFromLocationName
方法的the documentation:
如果未找到匹配项或没有可用的后端服务,则返回null或空列表。
因此,要解决您的问题,您可以这样做:
if (addressList != null && !addressList.isEmpty()) {
Address address=addressList.get(0);
LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,80));
latitudeB=latLng.latitude;
longitudeB=latLng.longitude;
} else {
Toast.makeText(getApplicationContext(), "No location found",
Toast.LENGTH_LONG).show();
}