嘿当我运行应用程序时,它会给出错误java.lang.IllegalArgumentException:listener == null,它告诉侦听器为null。
我的示例代码在这里:
public class HelloAndroidGpsActivity extends Activity {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonGetLocationClick();
}
});
}
/** Gets the current location and update the mobileLocation variable*/
private void getCurrentLocation() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("mobile location manager is ="+locManager);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
locListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
System.out.println("mobile location is in listener1");
}
@Override
public void onProviderEnabled(String provider) {
System.out.println("mobile location is in listener2");
}
@Override
public void onProviderDisabled(String provider) {
System.out.println("mobile location is in listener3");
}
@Override
public void onLocationChanged(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
}
};
System.out.println("after setting listener");
}
private void buttonGetLocationClick() {
getCurrentLocation();
System.out.println("mobile location is ="+mobileLocation);
if (mobileLocation != null) {
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n"
+ altitiude + "\n" + accuracy + "\n" + time);
} else {
editTextShowLocation.setText("Sorry, location is not determined");
}
}
}
文本框中的输出为“抱歉,位置未确定” 如果有人能告诉我这是什么问题,请帮助我。 谢谢
答案 0 :(得分:3)
在使用之前初始化侦听器。
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
此时,locListener为null,您在此代码行之后初始化它。这可能是原因。
所以重新排列你的代码行;
locListener = new LocationListener() {...};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
希望这可能有助于解决您的问题...