0

It does not locate the nearest user from where one is

I added a user Id in the firebase database but there is no progress

public class CustomerMapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
LocationRequest mLocationRequest;


private FusedLocationProviderClient fusedLocationClient;
private Button mLogout, mRequest;

private LatLng custLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_customer_map);
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mLogout = (Button) findViewById(R.id.logout);
    mRequest = (Button) findViewById(R.id.request);
    mLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(CustomerMapActivity.this,LoginActivity.class));

        }
    });
    mRequest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String publictoiletmanagerId = FirebaseAuth.getInstance().getCurrentUser().getUid();

            DatabaseReference ref = FirebaseDatabase.getInstance().getReference("customerRequest");
            GeoFire geoFire = new GeoFire(ref);
            geoFire.setLocation(publictoiletmanagerId, new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));

            custLocation = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            mMap.addMarker(new MarkerOptions().position(custLocation).title("Located here"));

            mRequest.setText("Locating the nearest public toilet for you...");
        }
    });
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    buildGoogleApiClient();
    mMap.setMyLocationEnabled(true);
}

protected synchronized  void buildGoogleApiClient(){
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;

    LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

}

@Override
public void onConnected(@Nullable Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                    }
                }
            });
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}

@Override
protected void onStop() {
    super.onStop();

}
}

and here is the logcat error:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.demoapp, PID: 30900 java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference at com.example.demoapp.CustomerMapActivity$2.onClick(CustomerMapActivity.java:73) at android.view.View.performClick(View.java:5232) at android.view.View$PerformClick.run(View.java:21289) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:168) at android.app.ActivityThread.main(ActivityThread.java:5885) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

The result is that it is supposed to locate the nearest user but the application keeps crashing

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
mutava
  • 1
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Bart Friederichs Mar 25 '19 at 08:56
  • 1
    The application crashes because of a `NullPointerException`, and it even tells you where it happens: CustomerMapActivity.java, line 73. – Bart Friederichs Mar 25 '19 at 08:57
  • Your variable `mLastLocation` has `null` value. – Boken Mar 25 '19 at 09:06
  • @Boken now how should I go about this – mutava Mar 25 '19 at 09:24
  • 1
    Probably method `onLocationChanged()` it is never called. You can sen breakpoint and test it (maybe there is no location enabled in device or user did not grant permission)? – Boken Mar 25 '19 at 09:27
  • the user does activate the location services and there location is spotted. So there is this button which is mRequest that allows the customer to locate the nearest person. When i tap on it this causes the application to crash thus sending this error – mutava Mar 25 '19 at 10:00
  • If the `mRequest` button is pressed before the `onLocationChanged()` callback method has run, then `mLastLocation` is `null`. I don't see you requesting location updates with `mLocationRequest` anywhere in the code given, so `onLocationChanged()` isn't going to be triggered. – Markus Kauppinen Mar 25 '19 at 10:20
  • okay let me try it out – mutava Mar 25 '19 at 11:50

0 Answers0