2016-06-28 28 views
1
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(); 
    } 
} 
+0

'如果(位置= NULL ||! location.equals(「」))'應該是'if(location!= null &&!location.equals(「」))' –

+0

發佈logcat錯誤信息 –

+0

java.lang.NullPointerException:嘗試從字段'double com .google.android.gms.maps.model.LatLng.latitude'放在空對象引用上 –

回答

0

如果location等於空字符串""然後location != null將是真實的,它會進入到if語句

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

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" /> 

希望它工作..

相關問題