我希望只获得以下数值。我如何阻止听众?我得到了值,然后在onLocationChanged()
中removeUpdates()
方法给了我一个空指针异常。所有这些都是通过点击按钮调用的
public void onLocationChanged(Location loc) {
locationManager.removeUpdates(this);
//editLocation.setText("");
//pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
//Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
//Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
String StreetName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
locationManager=null;
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
if (addresses.size() > 0)
System.out.println(addresses.get(0).getThoroughfare());
StreetName=addresses.get(0).getThoroughfare();
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
//editLocation.setText(s);
Toast.makeText(
getBaseContext(),
"Location: " + s, Toast.LENGTH_SHORT).show();
Toast.makeText(
getBaseContext(),
"Street Name: " + StreetName, Toast.LENGTH_LONG).show();
//locationManager.removeUpdates(locationListener);
}
按钮
public void Punchout(View view) {
boolean hasNetwrokProvider;
Toast.makeText(getApplicationContext(), "Getting Location", Toast.LENGTH_LONG).show();
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, locationListener);
在OnCreate之前:
private LocationManager locationManager;
private LocationListener locationListener;
答案 0 :(得分:0)
我看到了问题。您正在Punchout()
方法中创建局部变量,而不是使用Activity中定义的实例变量。
只需确保您始终使用实例变量,以便可以在onLocationChanged()
public void Punchout(View view) {
boolean hasNetwrokProvider;
Toast.makeText(getApplicationContext(), "Getting Location", Toast.LENGTH_LONG).show();
/* These lines created local variables:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
*/
//use the instance variables instead:
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, locationListener);
}