0

My app cannot get the longitude and latitude of the current online user and store it in a firebase database, the database keeps on being empty even when there is a user that is currently online. At times the app keeps crashing. I want to save the longitude and latitude of the user that is online into the firebase database using Geofire but it seems that it's not even getting the longitude and latitude of the current online user because it's returning null at times. I don't know what is the issue.

Here is my code.

        public class DriversMapsActivity extends FragmentActivity implements OnMapReadyCallback,
                        GoogleApiClient.ConnectionCallbacks,
                        GoogleApiClient.OnConnectionFailedListener,
                        com.google.android.gms.location.LocationListener {
                
                    private GoogleMap mMap;
                    private GoogleApiClient googleApiClient;
                    private Location lastLocation;
                    private LocationRequest locationRequest;
                    public static final int PERMISSION_FINE_LOCATION = 99;
                
                @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_drivers_maps);
                        driverSetting = findViewById(R.id.driver_maps_setting);
                        logoutBtn = findViewById(R.id.driver_maps_logout);
                        mAuth = FirebaseAuth.getInstance();
                
                SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                                .findFragmentById(R.id.map);
                        mapFragment.getMapAsync(this);
                        checkLocationPermission();
                
                @Override
                    public void onMapReady(GoogleMap googleMap) {
                        mMap = googleMap;
                
                        buildGoogleApiClient();
                
                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        mMap.setMyLocationEnabled(true);
                
                    }
                
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        locationRequest = new LocationRequest();
                        locationRequest.setInterval(1000);
                        locationRequest.setFastestInterval(1000);
                        locationRequest.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;
                        }
                        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
                
                    }
                
                    @Override
                    public void onConnectionSuspended(int i) {
                
                    }
                
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                
                    }
                
                    @Override
                    public void onLocationChanged(Location location) {
                       // if (getApplicationContext()!=null){
                            if (location !=null && mMap !=null){
                                try {
                
                                lastLocation = location;
                                LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
                                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                                mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
                
                                String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
                                DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
                                GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
                                geoFireDriverAvailability.setLocation(userID,new GeoLocation(location.getLatitude(),location.getLongitude()));
                
                }catch (Exception e){
                                    Toast.makeText(DriversMapsActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
                                }
                
                        }
                
                    }
                    protected synchronized void buildGoogleApiClient(){
                        googleApiClient = new GoogleApiClient.Builder(this)
                                .addConnectionCallbacks(this)
                                .addOnConnectionFailedListener(this)
                                .addApi(LocationServices.API)
                                .build();
                
                        googleApiClient.connect();
                    }
                
                    @Override
                    protected void onStop() {
                        super.onStop();
                
                        String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
                        DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
                        GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
                        geoFireDriverAvailability.removeLocation(userID);
                
                 }
                
                    public boolean checkLocationPermission() {
                        if (ContextCompat.checkSelfPermission(DriversMapsActivity.this,
                                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(DriversMapsActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
                            }
                        }
                        return true;
                    }
                }

I have added all these permissions in the manifest.

        <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.ACCESS_COARSE_LOCATION" />
            

Here is the error from the logcat

            E/AndroidRuntime: FATAL EXCEPTION: main
                Process: com.elijah.ukeme.ride_booking_app, PID: 12273
                java.lang.NoSuchMethodError: No virtual method setValueAsync(Ljava/lang/Object;Ljava/lang/Object;)Lcom/google/api/core/ApiFuture; in class Lcom/google/firebase/database/DatabaseReference; or its super classes (declaration of 'com.google.firebase.database.DatabaseReference' appears in /data/app/com.elijah.ukeme.ride_booking_app-1/base.apk:classes3.dex)
                    at com.firebase.geofire.GeoFire.setLocation(GeoFire.java:178)
                    at com.firebase.geofire.GeoFire.setLocation(GeoFire.java:149)
                    at com.elijah.ukeme.ride_booking_app.activity.DriversMapsActivity.onLocationChanged(DriversMapsActivity.java:224)
                    at com.google.android.gms.internal.location.zzay.notifyListener(Unknown Source)
                    at com.google.android.gms.common.api.internal.ListenerHolder.zaa(com.google.android.gms:play-services-base@@18.0.1:2)
                    at com.google.android.gms.common.api.internal.zacb.run(com.google.android.gms:play-services-base@@18.0.1)
                    at android.os.Handler.handleCallback(Handler.java:836)
                    at android.os.Handler.dispatchMessage(Handler.java:103)
                    at android.os.Looper.loop(Looper.java:203)
                    at android.app.ActivityThread.main(ActivityThread.java:6275)
                    at java.lang.reflect.Method.invoke(Native Method)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Pavindu
  • 2,684
  • 6
  • 44
  • 77
Ukeme Elijah
  • 157
  • 3
  • 13
  • One (possibly) unrelated point: in your `onLocationChanged` you check if `lastLocation != null` which, without seeing any other code, is going to be null initially and therefore the condition is never true - I suspect you want `if (location != null)` to verify the incoming location is valid. – Computable May 18 '22 at 17:16
  • the app keeps on crashing when I remove that line of code, Please could that be the reason that I am not getting the latitude and longitude of the place? – Ukeme Elijah May 20 '22 at 17:29
  • don't remove it - change it to `if (location != null)` – Computable May 20 '22 at 17:45
  • ok. let me try it – Ukeme Elijah May 20 '22 at 17:46
  • sorry my PC went down yesterday so that's why I couldn't get back to you. I have changed the stuff as you instructed but the app cannot open. Its keeps crashing when I tried to go to that activity but if I use emulator it's not crashing but as you know that emulator cannot track my current location as it will only make use of the system lastknownlocation. I don't know why it's crashing but if I change the if statement to if(lastLocation !=null) it's not crashing again which means that the app is unable to get the longitude and latitude of my current location. Please what should I do? – Ukeme Elijah May 21 '22 at 10:18
  • It's possible to get location updates _before_ you have the map initialized so the `mMap` reference likely is not set up yet - therefore modify your condition to `if (location != null && mMap != null)` - when the map becomes ready and the locations are being generated then it should become true - if you have any more crashes please post the logcat exception trace (makes things easier). – Computable May 21 '22 at 10:32
  • Let me try it, concerning posting the logcat, I can't really get it since I am testing it on a mobile phone instead of a virtual device. I don't know if there is a way to get a logcat while testing an app on a physical phone rather than a virtual device – Ukeme Elijah May 21 '22 at 10:59
  • I have edited the code and add the error that I got from the logcat, please check it out for me. thanks – Ukeme Elijah May 21 '22 at 12:55

0 Answers0