我在我的 android 代码中使用 Google 地图,我想使用“Geocoder”类获取我的位置地址。
这是我正在使用的代码
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但我在这一行得到一个 NullPointerException :
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
这是完整的代码
public class MainActivity extends Activity implements LocationListener {
private TextView cityText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView hum;
private ImageView imgView;
Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat;
double lng;
public static String resultStr;
private String latituteField;
private String longitudeField;
private LocationManager locationManager;
private String provider;
public String cityName;
public Location loc;
@Override
public void onLocationChanged(android.location.Location loc) {
// TODO Auto-generated method stub
String longitude = "Longitude: " +loc.getLongitude();
// Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
//Log.v(TAG, latitude);
//String
cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
// editLocation.setText(s);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("hi","hi");
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("addresses",addresses.toString());
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
android.location.Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
System.out.println("location not available");
}
// String city ="lat=%f&lon=%f,"
/////////////////////////
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
JSONWeatherTask task = new JSONWeatherTask();
//task.execute(new String[]{city});
task.execute(new String[]{cityName});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
@Override
protected Weather doInBackground(String... params) {
Weather weather = new Weather();
String data = ( (new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
// Let's retrieve the icon
weather.iconData = ( (new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
@Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
imgView.setImageBitmap(img);
}
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 275.15)) + "°C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "°");
}
}
@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
}
}
这是logCat:
11-09 04:30:55.723: E/AndroidRuntime(1868): FATAL EXCEPTION: main
11-09 04:30:55.723: E/AndroidRuntime(1868): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.survivingwithandroid.weatherapp/com.survivingwithandroid.weatherapp.MainActivity}: java.lang.NullPointerException
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.os.Handler.dispatchMessage(Handler.java:99)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.os.Looper.loop(Looper.java:137)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-09 04:30:55.723: E/AndroidRuntime(1868): at java.lang.reflect.Method.invokeNative(Native Method)
11-09 04:30:55.723: E/AndroidRuntime(1868): at java.lang.reflect.Method.invoke(Method.java:525)
11-09 04:30:55.723: E/AndroidRuntime(1868): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-09 04:30:55.723: E/AndroidRuntime(1868): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-09 04:30:55.723: E/AndroidRuntime(1868): at dalvik.system.NativeStart.main(Native Method)
11-09 04:30:55.723: E/AndroidRuntime(1868): Caused by: java.lang.NullPointerException
11-09 04:30:55.723: E/AndroidRuntime(1868): at com.survivingwithandroid.weatherapp.MainActivity.onCreate(MainActivity.java:127)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.Activity.performCreate(Activity.java:5133)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-09 04:30:55.723: E/AndroidRuntime(1868): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)