在AndroidStudio中运行以下代码后,获取位置坐标的Nullpointer异常

在AndroidStudio中运行以下代码后,获取位置坐标的Nullpointer异常,android,nullpointerexception,location,Android,Nullpointerexception,Location,在我的代码中,我一直在尝试使用getLastKnownLocation()获取用户的位置坐标 仅当MLocationPermissionGrassed设置为true时,才应调用此方法。在获得位置坐标后,我使用createLocation方法将它们存储在一个对象中,createLocation将2个double作为参数。但是,在到达创建地图的活动之前,我收到了错误信息: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.rec

在我的代码中,我一直在尝试使用getLastKnownLocation()获取用户的位置坐标 仅当MLocationPermissionGrassed设置为true时,才应调用此方法。在获得位置坐标后,我使用createLocation方法将它们存储在一个对象中,createLocation将2个double作为参数。但是,在到达创建地图的活动之前,我收到了错误信息:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.recipes, PID: 18666
java.lang.NullPointerException: Attempt to invoke virtual method 'double 
android.location.Location.getLatitude()' on a null object reference
    at com.example.recipes.views.activities.discovery.DiscoveryWorld$2.onComplete(DiscoveryWorld.java:187)
    at com.google.android.gms.tasks.zzj.run(com.google.android.gms:play-services-tasks@@17.2.0:4)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
我已经在AndroidManifest.xml中添加了所有必要的需求,包括permissions+API键

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这是我正在运行以获取用户位置的类的一部分:

package com.example.recipes.views.activities.discovery;

//Whole bunch of imports



/**
 * This Class will open a map for the user and displays recipes uploaded by other users on the map.
 * The location at which users posted their recipes will be saved in the database.
 * By clicking on a marker of a recipe the user will receive more details about said recipe
 */
public class DiscoveryWorld extends AppCompatActivity implements OnMapReadyCallback {

//To be used for the latitude and longitude coordinates
double lat_test;
double lon_test;


public static UserLocation mulocation = new UserLocation();

private MapView mMapView;
private FusedLocationProviderClient mFusedLocationProviderClient;

@Override
protected void onCreate (Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_discovery_world);

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);


    }

//Get user location
public void getLastKnownLocation () {
    System.out.println("getLastKnownLocation was called");
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        System.out.println("failed");
        return;
    }
    mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
        @Override
        public void onComplete(@NonNull Task<Location> task) {
            if (task.isSuccessful()) {
                Location location = task.getResult();
                lat_test = location.getLatitude(); // <- gets NullPointerException error
                lon_test = location.getLongitude(); // <- gets NullPointerException error
                System.out.println(lon_test + "and" + lat_test);
//                    lat_test = 25;
//                    lon_test = 35;
                System.out.println("hello!!!");
                createLocation(lat_test, lon_test);
            }
        }
    });
}

@Override
public void onRequestPermissionsResult ( int requestCode,
                                         @NonNull String permissions[],
                                         @NonNull int[] grantResults){
    mLocationPermissionGranted = false;
    switch (requestCode) {
        case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
                getLastKnownLocation();
            }
        }
    }
    System.out.println("LocationPerms: " + mLocationPermissionGranted);
}

@Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
    System.out.println("LocationPerms: " + mLocationPermissionGranted);
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case PERMISSIONS_REQUEST_ENABLE_GPS: {
            if (mLocationPermissionGranted) {
                getLastKnownLocation();
            } else {
                getLocationPermission();
            }
        }
    }

}
package com.example.recipes.views.activities.discovery;
//一大堆进口货
/**
*这个类将为用户打开一个地图,并在地图上显示其他用户上传的食谱。
*用户发布食谱的位置将保存在数据库中。
*通过单击配方的标记,用户将收到有关所述配方的更多详细信息
*/
公共类DiscoveryWorld扩展了AppCompatActivity在MapreadyCallback上的实现{
//用于纬度和经度坐标
双拉脱试验;
双lonu试验;
public static UserLocation mulocation=new UserLocation();
私人地图视图;
私有FusedLocationProviderClient mFusedLocationProviderClient;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u discovery\u world);
mFusedLocationProviderClient=LocationServices.getFusedLocationProviderClient(此);
}
//获取用户位置
公共无效getLastKnownLocation(){
System.out.println(“调用了getLastKnownLocation”);
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予){
System.out.println(“失败”);
返回;
}
mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
if(task.issusccessful()){
位置=task.getResult();

lat_test=location.getLatitude();//您使用哪种设备?如果您使用模拟器,请确保使用安装了Google API或Google Play Store的系统映像


这是否回答了您的问题?基本上是因为一些可能的原因,如
task
可能为null或
task.getResult()
可以为空,尝试找出您的案例的问题欢迎使用堆栈溢出!我建议将您的问题稍微细化一点,以使其更具体地反映您的问题。问题不是您获得了NPE,而是您的位置提供商给了您一个空位置。另外,请看一下如何生成堆栈溢出,发布所有不相关的内容nt代码对任何人的回答都不是很有帮助。啊,我理解NullPointerException到底是什么,我只是不确定location对象为什么为null,谢谢帮助。所以实际的任务对象是null…嗯,我来看看,thx!将其编辑为包含不太相关的代码。我希望问题也能更清楚一点嗯,我使用的是三星Galaxy S7。由于模拟器没有实际的gps信号,它根本不应该给我一个位置。但是,我的S7应该给我一个位置,而不是NPE。