我是Android的新手,需要帮助来解决这个问题。我有一个实现LocationListener的服务。当应用程序崩溃时,我收到以下错误。请解释我应该在我的代码中做出哪些更改。我已经参考了许多LocationListener和Services教程,但无法准确地弄清楚发生了什么。请逐步清除我的疑虑。我发布了我的代码和错误日志:
新错误日志:
03-22 01:42:20.249: E/AndroidRuntime(6537): FATAL EXCEPTION: main
03-22 01:42:20.249: E/AndroidRuntime(6537): java.lang.NullPointerException
03-22 01:42:20.249: E/AndroidRuntime(6537): at com.example.broadcast.Ser.onLocationChanged(Ser.java:131)
03-22 01:42:20.249: E/AndroidRuntime(6537): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:263)
03-22 01:42:20.249: E/AndroidRuntime(6537): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:196)
03-22 01:42:20.249: E/AndroidRuntime(6537): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:212)
03-22 01:42:20.249: E/AndroidRuntime(6537): at android.os.Handler.dispatchMessage(Handler.java:99)
03-22 01:42:20.249: E/AndroidRuntime(6537): at android.os.Looper.loop(Looper.java:137)
03-22 01:42:20.249: E/AndroidRuntime(6537): at android.app.ActivityThread.main(ActivityThread.java:4960)
03-22 01:42:20.249: E/AndroidRuntime(6537): at java.lang.reflect.Method.invokeNative(Native Method)
03-22 01:42:20.249: E/AndroidRuntime(6537): at java.lang.reflect.Method.invoke(Method.java:511)
03-22 01:42:20.249: E/AndroidRuntime(6537): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
03-22 01:42:20.249: E/AndroidRuntime(6537): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
03-22 01:42:20.249: E/AndroidRuntime(6537): at dalvik.system.NativeStart.main(Native Method)
这是我的(新)服务代码:
public class Ser extends Service implements LocationListener{
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String l1=String.valueOf(latitude);
String l2=String.valueOf(longitude);
}
}
return location;
}
}
public void onLocationChanged(Location location) {
if(location!=null)
{
double latitude =location.getLatitude();
double longitude = location.getLongitude();
Log.i("msg","in locationchanged");
}
}
答案 0 :(得分:2)
在
public void onLocationChanged(Location location) {
double latitude =location.getLatitude();
double longitude = location.getLongitude();
Log.i("msg","in locationchanged");
}
检查location
是否为空。
public void onLocationChanged(Location location) {
if (location == null) return;
double latitude =location.getLatitude();
double longitude = location.getLongitude();
Log.i("msg","in locationchanged");
}
答案 1 :(得分:1)
getLastKnownLocation()
可以返回null
,因此您应该在调用location.getLatitude()
和location.getLongitude()