给 java.lang.NullPointerException: 当我点击当前位置按钮时
Give java.lang.NullPointerException: when i click on current location button
当我单击当前按钮以获取用户的当前位置时,即使我检查 fusedapi 是否被授予,也会给出 nullpointer 异常,并且当用户允许当前位置访问时,我会检索当前位置,但它显示错误
地图片段
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_map, container, false);
latlng.add(new LatLng(22.32371, 73.16409));
latlng.add(new LatLng(22.32737, 73.17566));
latlng.add(new LatLng(22.28, 73.1903696));
latlng.add(new LatLng(22.334, 73.21853));
latlng.add(new LatLng(22.40303, 73.22369));
latlng.add(new LatLng(22.55148, 72.97035));
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(this);
askPermission();
createGoogleApi();
mbtn = rootview.findViewById(R.id.myLocationButton);
mbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getcurrentmarker();
}
});
return rootview;
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mgoogleMap = googleMap;
mgoogleMap.setOnMarkerClickListener(this);
}
@Override
public void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
@Override
public void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
private void createGoogleApi()
{
Log.d(TAG, "createGoogleApi()");
if ( googleApiClient == null )
{
googleApiClient = new GoogleApiClient.Builder( getContext() )
.addConnectionCallbacks(this)
.addOnConnectionFailedListener( this )
.addApi(LocationServices.API)
.build();
}
}
// Check for permission to access Location
private boolean checkPermission() {
Log.d(TAG, "checkPermission()");
// Ask for permission if it wasn't granted yet
return (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// Asks for permission
private void askPermission() {
Log.d(TAG, "askPermission()");
ActivityCompat.requestPermissions(
MapFragment.super.getActivity(),
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION
);
}
// Verify user's response of the permission requested
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQ_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "Permission", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
// App cannot work without the permissions
private void permissionsDenied() {
Log.w(TAG, "permissionsDenied()");
}
// Start location Updates
private void startLocationUpdates(){
Log.i(TAG, "startLocationUpdates()");
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(6000)
.setFastestInterval(5000);
//movement in meter
if ( checkPermission() )
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged ["+location+"]");
lastLocation = location;
writeActualLocation(location);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "onConnected()");
getLastKnownLocation();
}
// GoogleApiClient.ConnectionCallbacks suspended
@Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "onConnectionSuspended()");
}
// GoogleApiClient.OnConnectionFailedListener fail
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.w(TAG, "onConnectionFailed()");
}
// Get last known location
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation()");
if ( checkPermission() ) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if ( lastLocation != null ) {
Log.i(TAG, "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w(TAG, "No location retrieved yet");
startLocationUpdates();
}
}
else askPermission();
}
private void writeActualLocation(Location location)
{
lastLocation = location;
showmarker(latlng);
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
private void getcurrentmarker()
{
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mgoogleMap.setMyLocationEnabled(true);
mgoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mgoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), 14));
}
private void showmarker(List<LatLng> positions)
{
Log.d(TAG,"show");
if(!markers.equals(null))
{
markers.clear();
}
if ( marker != null ) {
marker.remove();
}
for (LatLng position : positions) {
Marker marker = mgoogleMap.addMarker(
new MarkerOptions()
.position(position)
.visible(false)); // Invisible for now
markers.add(marker);
}
for (Marker marker : markers) {
if (SphericalUtil.computeDistanceBetween(new LatLng(lastLocation.getLatitude(),lastLocation.getLongitude()), marker.getPosition()) < 400) {
marker.setVisible(true);
float zoom = 14f;
CameraUpdate cameraUpdate1 = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), zoom);
mgoogleMap.animateCamera(cameraUpdate1);
}
}
}
@Override
public boolean onMarkerClick(Marker marker)
{
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment(lastLocation,marker.getPosition());
bottomSheetFragment.show(getFragmentManager(), bottomSheetFragment.getTag());
return false;
}
}
清单
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在连接 googleapiclient 之前,我请求获得当前位置的许可,然后检索当前位置,然后单击当前位置按钮
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.eats.Fragment.MapFragment.getcurrentmarker(MapFragment.java:256)
检查位置是否处于启用/禁用状态
如果位置被禁用,则结果将为空。
我推荐使用 FusedLocationProviderClient
然后做这样的事情:
if (handleLocationPermission()) {
context?.let {
fusedLocationProvider = LocationServices.getFusedLocationProviderClient(it)
if (ContextCompat.checkSelfPermission(it, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider.lastLocation
.addOnSuccessListener { location ->
if (location != null) {
writeLastLocation(location.latitude, location.longitude)
}
}
}
}
}
}
```
当我单击当前按钮以获取用户的当前位置时,即使我检查 fusedapi 是否被授予,也会给出 nullpointer 异常,并且当用户允许当前位置访问时,我会检索当前位置,但它显示错误
地图片段
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_map, container, false);
latlng.add(new LatLng(22.32371, 73.16409));
latlng.add(new LatLng(22.32737, 73.17566));
latlng.add(new LatLng(22.28, 73.1903696));
latlng.add(new LatLng(22.334, 73.21853));
latlng.add(new LatLng(22.40303, 73.22369));
latlng.add(new LatLng(22.55148, 72.97035));
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(this);
askPermission();
createGoogleApi();
mbtn = rootview.findViewById(R.id.myLocationButton);
mbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getcurrentmarker();
}
});
return rootview;
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mgoogleMap = googleMap;
mgoogleMap.setOnMarkerClickListener(this);
}
@Override
public void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
@Override
public void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
private void createGoogleApi()
{
Log.d(TAG, "createGoogleApi()");
if ( googleApiClient == null )
{
googleApiClient = new GoogleApiClient.Builder( getContext() )
.addConnectionCallbacks(this)
.addOnConnectionFailedListener( this )
.addApi(LocationServices.API)
.build();
}
}
// Check for permission to access Location
private boolean checkPermission() {
Log.d(TAG, "checkPermission()");
// Ask for permission if it wasn't granted yet
return (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// Asks for permission
private void askPermission() {
Log.d(TAG, "askPermission()");
ActivityCompat.requestPermissions(
MapFragment.super.getActivity(),
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION
);
}
// Verify user's response of the permission requested
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQ_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "Permission", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
// App cannot work without the permissions
private void permissionsDenied() {
Log.w(TAG, "permissionsDenied()");
}
// Start location Updates
private void startLocationUpdates(){
Log.i(TAG, "startLocationUpdates()");
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(6000)
.setFastestInterval(5000);
//movement in meter
if ( checkPermission() )
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged ["+location+"]");
lastLocation = location;
writeActualLocation(location);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "onConnected()");
getLastKnownLocation();
}
// GoogleApiClient.ConnectionCallbacks suspended
@Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "onConnectionSuspended()");
}
// GoogleApiClient.OnConnectionFailedListener fail
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.w(TAG, "onConnectionFailed()");
}
// Get last known location
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation()");
if ( checkPermission() ) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if ( lastLocation != null ) {
Log.i(TAG, "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w(TAG, "No location retrieved yet");
startLocationUpdates();
}
}
else askPermission();
}
private void writeActualLocation(Location location)
{
lastLocation = location;
showmarker(latlng);
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
private void getcurrentmarker()
{
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mgoogleMap.setMyLocationEnabled(true);
mgoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mgoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), 14));
}
private void showmarker(List<LatLng> positions)
{
Log.d(TAG,"show");
if(!markers.equals(null))
{
markers.clear();
}
if ( marker != null ) {
marker.remove();
}
for (LatLng position : positions) {
Marker marker = mgoogleMap.addMarker(
new MarkerOptions()
.position(position)
.visible(false)); // Invisible for now
markers.add(marker);
}
for (Marker marker : markers) {
if (SphericalUtil.computeDistanceBetween(new LatLng(lastLocation.getLatitude(),lastLocation.getLongitude()), marker.getPosition()) < 400) {
marker.setVisible(true);
float zoom = 14f;
CameraUpdate cameraUpdate1 = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), zoom);
mgoogleMap.animateCamera(cameraUpdate1);
}
}
}
@Override
public boolean onMarkerClick(Marker marker)
{
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment(lastLocation,marker.getPosition());
bottomSheetFragment.show(getFragmentManager(), bottomSheetFragment.getTag());
return false;
}
}
清单
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在连接 googleapiclient 之前,我请求获得当前位置的许可,然后检索当前位置,然后单击当前位置按钮
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.eats.Fragment.MapFragment.getcurrentmarker(MapFragment.java:256)
检查位置是否处于启用/禁用状态 如果位置被禁用,则结果将为空。
我推荐使用 FusedLocationProviderClient
然后做这样的事情:
if (handleLocationPermission()) {
context?.let {
fusedLocationProvider = LocationServices.getFusedLocationProviderClient(it)
if (ContextCompat.checkSelfPermission(it, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider.lastLocation
.addOnSuccessListener { location ->
if (location != null) {
writeLastLocation(location.latitude, location.longitude)
}
}
}
}
}
}
```