Java android studio中的空指针错误

Java android studio中的空指针错误,java,android,android-studio,Java,Android,Android Studio,我的代码抛出空指针错误并使整个应用程序崩溃。我已经用按钮id检查了它是否正确,但找不到错误。我正在尝试将此功能分配给按钮。 基本上我想访问当前位置经纬度,并在那里显示一个标记。所以,如果你有任何备用代码也可以 public void onPing(View view) { if (view.getId() == R.id.button2) { mMap.clear(); LocationManager lm = (LocationManager) get

我的代码抛出空指针错误并使整个应用程序崩溃。我已经用按钮id检查了它是否正确,但找不到错误。我正在尝试将此功能分配给按钮。 基本上我想访问当前位置经纬度,并在那里显示一个标记。所以,如果你有任何备用代码也可以

 public void onPing(View view) {
    if (view.getId() == R.id.button2) {
        mMap.clear();
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        subLoc = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(subLoc).title("Current Position"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(subLoc));

来自
lm.getLastKnownLocation(LocationManager.GPS\U提供商)的位置可以为空

 if(location != null){
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        subLoc = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(subLoc).title("Current Position"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(subLoc));
 }

发布错误/崩溃日志发布堆栈跟踪另一个
LocationManager.getLastKnownLocation
可能返回null,并且在您的案例中返回null