get Last Location返回null对象引用错误

时间:2016-06-13 22:25:41

标签: java android google-maps

嘿伙计们,我的方法是返回我当前(最后知道的)位置,这是杀死我的应用程序。我的错误日志没有显示出来,所以我能想到的唯一想法就是使用权限/位置类进行了一些操作。如果可以,我将它设置为拉取我的位置,否则返回预先存储的LatLng。请帮忙!这是我的代码

public LatLng getLocation(GoogleApiClient client) {

    if(client == null){
        Log.d(null, "error:null client");
    }else{
        if( ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location mLastLocation = FusedLocationApi.getLastLocation(client);
            return new LatLng(mLastLocation.getLongitude(), mLastLocation.getLatitude());
        }else{
            Log.d(null, "error:permission fail");
        }
    }
return harrys;
}

这是我的错误堆栈

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'double android.location.Location.getLongitude()'                                                              在com.example.kevin.memories.MapsActivity.getLocation(MapsActivity.java:251)                                                              at com.example.kevin.memories.MapsActivity.onMapReady(MapsActivity.java:93)                                                              在com.google.android.gms.maps.SupportMapFragment $ zza $ 1.zza(未知来源)                                                              在com.google.android.gms.maps.internal.zzo $ zza.onTransact(未知来源)                                                              在android.os.Binder.transact(Binder.java:387)                                                              在wv.a(:com.google.android.gms.DynamiteModulesB:82)                                                              at maps.ag.t $ 5.run(未知来源)                                                              在android.os.Handler.handleCallback(Handler.java:739)                                                              在android.os.Handler.dispatchMessage(Handler.java:95)                                                              在android.os.Looper.loop(Looper.java:158)                                                              在android.app.ActivityThread.main(ActivityThread.java:7224)                                                              at java.lang.reflect.Method.invoke(Native Method)                                                              在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1230)                                                              在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

2 个答案:

答案 0 :(得分:0)

null object reference表示您引用尚未存在的对象。所以这可能意味着在对象的初始化之前,您对该对象的调用是第一次。 如果确实能够获取某些内容,请尝试记录您的getLastLocation

另请查看此SO thread以获取其他答案。

答案 1 :(得分:0)

确保仅在GoogleApiClient连接后调用getLastLocation(客户端)。您可以使用client.isConnected()方法检查它,也可以从onConnected方法调用它。