我正试图通过来自http://www.hrupin.com/2011/04/android-gps-using-how-to-get-current-location-example的ihrupin使用此代码来获取地址
在我添加地理编码以获取onLocationChanged
以下是代码:
buttonGetLocation.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try
{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch (Exception ex)
{
}
try
{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch (Exception ex)
{
}
// don't start listeners if no provider is enabled
if (gps_enabled)
{
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled)
{
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
});
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
//
String address = "Adress : "+goToGeocoder(location.getLatitude().getLongitude());
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + address);
progress.setVisibility(View.GONE);
}
}
Context context;
public String goToGeocoder(String ll)
{
List<Address> almt;
String alamat = null;
double lat,lng;
StringBuilder sb = new StringBuilder();
lat = Double.parseDouble(ll.substring(0,ll.indexOf(",")-1));
lng = Double.parseDouble(ll.substring(ll.indexOf(",")+1));
try
{
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
almt = geocoder.getFromLocation(lat, lng, 5);
if(almt.size()>0)
{
Address almtSkrng = almt.get(0);
String admin_area = sb.append(almtSkrng.getAdminArea()).toString();
if(almtSkrng.getAddressLine(0).equals(null) || almtSkrng.getAddressLine(0).equals(""))
{
alamat = almtSkrng.getFeatureName();
}
alamat = almtSkrng.getAddressLine(0)+" "+almtSkrng.getAdminArea();
//temp_koordinate.setAlamat(alamat);
}
else
{
alamat = "";
//temp_koordinate.setAlamat(alamat);
}
}
catch(IOException e)
{
//
}
return alamat;
}
申请被强制关闭。
任何人都可以提供解决方案来解决这个问题吗? 非常感谢 亲切的问候
答案 0 :(得分:0)
在没有提供显示崩溃的日志(即堆栈跟踪)的情况下很难回答强制关闭的原因......
如果没有这些信息,答案可能是:
您需要处理地理编码返回null的情况。
if(almt != null) {
//do what you need to do
} else {
//handle the null situation here
}
或者你可以在你的try / catch语句中添加一个catch块来处理NullPointerException。