Android:位置经度的Nullpointer?

时间:2014-07-24 14:10:23

标签: android gps location locationmanager

我得到这个错误已经三天了(在它工作之前,所以......不知道):location.getLongitude(); nullpointer exception 我的简单代码(onCreate()的最后一个代码):

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Double latitudine=location.getLatitude();

我在最后一行得到了nullpointer ...我再说一遍:它正在工作...... 非常感谢。

logcat的:

07-24 16:11:23.125    1622-1622/it.avcommunication.tuodi E/dalvikvm﹕ Could not find class 'gpr', referenced from method gps.a
07-24 16:11:23.125    1622-1622/it.avcommunication.tuodi E/dalvikvm﹕ Could not find class 'gpr', referenced from method gps.a
07-24 16:11:23.125    1622-1622/it.avcommunication.tuodi E/dalvikvm﹕ Could not find class 'gpr', referenced from method gps.a
07-24 16:11:23.300    1622-1622/it.avcommunication.tuodi E/dalvikvm﹕ Could not find class 'com.google.android.gms.location.internal.ParcelableGeofence', referenced from method glt.a
07-24 16:11:24.350    1622-1622/it.avcommunication.tuodi E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{it.avcommunication.tuodi/it.avcommunication.tuodi.Negozi}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
        at android.app.ActivityThread.access$700(ActivityThread.java:140)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4921)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at it.avcommunication.tuodi.Negozi.onCreate(Negozi.java:233)
        at android.app.Activity.performCreate(Activity.java:5206)

2 个答案:

答案 0 :(得分:1)

如果设备之前没有位置锁定,则

getLastKnownLocation会返回null。

尝试启用GPS并检查。还可以尝试打开启用GPS的地图,这对我有用。

答案 1 :(得分:0)

试试这段代码:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
     5000, 10, this);

然后在onLocationChanged方法中尝试这样做:

public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}

别忘了实现LocationListener接口。

public class ActivityName extends Activity implements LocationListener {