我正在尝试制作一个天气应用程序,它使用 Geocoder 获取当前城市,然后使用 AsyncTask 从 api 获取天气数据,然后对其进行解析。但是当我在 AsyncTask 方法中输入当前城市时execute()
,我的应用程序崩溃了:
private double latitude;
private double longitude;
String address;
LocationManager lm;
LocationListener ll;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
address = getAddress(latitude, longitude); // getAddress() is below
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class myLocationListener implements LocationListener {
@Override
public void onLocationChanged(android.location.Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
String address = getAddress(latitude, longitude);
Task task = new Task(); // Task extends AsyncTask
task.execute(new String[] { address });
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getAddress(double lat, double lon) {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(
lat, lon, 10);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuffer str = new StringBuffer();
str.append(returnedAddress.getLocality());
str.append(",");
str.append(returnedAddress.getCountryName());
ret = str.toString();
} else {
ret = "No Address returned!";
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
我知道我的getAddress()
方法按预期工作。当我将一个城市和州硬编码到该address
领域时,它就像一个魅力。但是,当我调用我的getAddress()
方法并将其设置为address
,然后将其输入 时execute()
,应用程序崩溃并说getFromLocation()
返回 null。为什么会这样?这是我的代码的顺序吗?感谢您提前提供所有答案。