我无法理解为什么addresslist值为null

时间:2016-06-28 10:43:44

标签: android

EditText location_tf = (EditText) findViewById(R.id.mapsearchaddress);
String location = location_tf.getText().toString();
//Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addressList = null;

if (location != null || !location.equals("")) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        addressList = geocoder.getFromLocationName(location, 1);
    }
    catch (IOException e) {
        Toast.makeText(MapsActivity.this, "Addess not found", Toast.LENGTH_SHORT).show();
    }

    if (addressList != null && addressList.size() > 0) {
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
    else {
        Toast.makeText(MapsActivity.this, "Can't find address", Toast.LENGTH_SHORT).show();
    }
}

2 个答案:

答案 0 :(得分:0)

如果location等于空字符串"",那么location != null将为true,它将进入if语句

使用if(location != null && !location.equals(""))代替

答案 1 :(得分:0)

我通过轮询Geocoder找到并解决,直到我得到了一个结果。我是这样做的..

try {
    List<Address> geoResults = geocoder.getFromLocationName(location, 1);
    while (geoResults.size()==0) {
        geoResults = geocoder.getFromLocationName(location, 1);
    }
    if (geoResults.size()>0) {
        Address addr = geoResults.get(0);
        LatLng latLng = new LatLng(addr.getLatitude(), addr.getLongitude());
    }
} catch (Exception e) {
    System.out.print(e.getMessage());
}

这些是manifest.xml文件的权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

希望它有效..