如何修复空对象引用位置

时间:2019-11-09 00:45:31

标签: java android

尝试在onMapReady方法中获取位置时,我的应用程序出现问题。

我试图在不同的变量中获取经度和纬度,但是onMapReady方法仍然将其作为null。

在ToL的getLastLocation方法中,它显示了我的真实位置,但是当我在myLocation之外使用myLocation时,所得坐标为0.0 -0.0

public class MapFragment extends Fragment implements OnMapReadyCallback {

Location myLocation = null;
FusedLocationProviderClient fusedLocation;
private static final int Request_Code = 101;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

private void getLastLocation() {
    if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
    }
    Task<Location> task = fusedLocation.getLastLocation();
    task.addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if(location != null) {
                myLocation = location;
                Toast.makeText(getContext(), myLocation.getLatitude() + "" + myLocation.getLongitude(), Toast.LENGTH_SHORT).show(); // This correctly shows me my true location
            }
        }
    });
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.map_fragment, container, false);
    fusedLocation = LocationServices.getFusedLocationProviderClient(getActivity());
    getLastLocation();
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync( this);
    return v;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case Request_Code:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLastLocation();
            }
            break;
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    if (googleMap != null) {
        LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
        MarkerOptions marker = new MarkerOptions().position(latLng).title("Estas aquí");
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
        googleMap.addMarker(marker);
    }
 }
}

错误日志:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.mint, PID: 11019
    java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
    at com.example.mint.MapFragment.onMapReady(MapFragment.java:81)
    at com.google.android.gms.maps.zzak.zza(Unknown Source:2)
    at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source:12)
    at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source:12)
    at android.os.Binder.transact(Binder.java:667)
    at ck.b(:com.google.android.gms.dynamite_mapsdynamite@19629065@19.6.29 (100400-0):14)
    at com.google.android.gms.maps.internal.bb.a(:com.google.android.gms.dynamite_mapsdynamite@19629065@19.6.29 (100400-0):4)
    at com.google.maps.api.android.lib6.impl.bi.run(:com.google.android.gms.dynamite_mapsdynamite@19629065@19.6.29 (100400-0):2)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at ln.dispatchMessage(:com.google.android.gms.dynamite_mapsdynamite@19629065@19.6.29 (100400-0):5)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6672)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
    I/Process: Sending signal. PID: 11019 SIG: 9
Process 11019 terminated.

1 个答案:

答案 0 :(得分:0)

您的代码抛出nullPointerException,因为myLocation仍然为null,因此请尝试使用以下代码

public class MapFragment extends Fragment implements OnMapReadyCallback {

Location myLocation = null;
FusedLocationProviderClient fusedLocation;
private static final int Request_Code = 101;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

private void getLastLocation() {
    if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
    }
    Task<Location> task = fusedLocation.getLastLocation();
    task.addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if(location != null) {
                myLocation = location;

                //change was made here
                SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
                mapFragment.getMapAsync( this);
                Toast.makeText(getContext(), myLocation.getLatitude() + "" + myLocation.getLongitude(), Toast.LENGTH_SHORT).show(); // This correctly shows me my true location
            }
        }
    });
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.map_fragment, container, false);
    fusedLocation = LocationServices.getFusedLocationProviderClient(getActivity());
    getLastLocation();
    return v;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case Request_Code:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLastLocation();
            }
            break;
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    if (googleMap != null) {
        LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
        MarkerOptions marker = new MarkerOptions().position(latLng).title("Estas aquí");
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
        googleMap.addMarker(marker);
    }
 }
}