我正在使用Google Map Activity,当我编写Gibberish并命中"搜索"时,应用程序会粉碎。但是,它与真实位置完美搭配。我如何防止它崩溃?
我的代码:
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();
}
}
来自Geocoder.getFromLocationName
方法的文档:
如果找不到匹配或没有可用的后端服务,则返回空名单或空列表。
因此,要解决您的问题,您可以做:
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();
}
添加此检查,然后在代码中获得纬度和经度
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();
}
}