Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

java - Not able to upload GeoFire Location in firebase database

I just want to upload my location in firebase database using GeoFire.

    DatabaseReference onlineRef,CurrentUserRef,DriverLocationRef;
    GeoFire geoFire;
    ValueEventListener onlineValueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists())
                CurrentUserRef.onDisconnect().removeValue();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(HomeActivity.this,error.getMessage(), Toast.LENGTH_SHORT).show();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        onlineRef = FirebaseDatabase.getInstance().getReference().child(".info/connected");
        DriverLocationRef = FirebaseDatabase.getInstance().getReference(Common.Drivers_Location_Reference);
        CurrentUserRef = FirebaseDatabase.getInstance().getReference(Common.Drivers_Location_Reference).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        geoFire = new GeoFire(DriverLocationRef);
        registerOnlineSystem();
        getDeviceLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerOnlineSystem();
    }

    private void registerOnlineSystem() {
        onlineRef.addValueEventListener(onlineValueEventListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        geoFire.removeLocation(FirebaseAuth.getInstance().getCurrentUser().getUid());
        mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
        onlineRef.removeEventListener(onlineValueEventListener);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Get the location at the center of the map each time the camera moves
        mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                latLng = mMap.getCameraPosition().target;
            }
        });

        //reposition default GPS button on map
        if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null) {
            View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
            layoutParams.width = 100;
            layoutParams.height = 100;
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            layoutParams.setMargins(0, 0, 40, 40);
        }

        //check if GPS is enabled or not and then request user to enable it.
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(5000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        //Handles location settings turned on/off
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

        SettingsClient settingsClient = LocationServices.getSettingsClient(HomeActivity.this);
        Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());

        task.addOnSuccessListener(HomeActivity.this, locationSettingsResponse -> getDeviceLocation());

        task.addOnFailureListener(HomeActivity.this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                if (e instanceof ResolvableApiException) {
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    try {
                        resolvable.startResolutionForResult(HomeActivity.this, 51);
                    } catch (IntentSender.SendIntentException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    }
    private void getDeviceLocation() {
        mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                    mLastKnownLocation = task.getResult();
                    if (mLastKnownLocation != null) {
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(),
                                mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                    } else {
                        locationRequest = new LocationRequest();
                        locationRequest.setInterval(10000);
                        locationRequest.setFastestInterval(5000);
                        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                        locationCallback = new LocationCallback() {
                            @Override
                            public void onLocationResult(LocationResult locationResult) {
                                super.onLocationResult(locationResult);
                                LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),locationResult.getLastLocation().getLongitude());
                                mLastKnownLocation = locationResult.getLastLocation();
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition, DEFAULT_ZOOM));
                                //mFusedLocationProviderClient.removeLocationUpdates(locationCallback);

                                geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(),
                                        new GeoLocation(locationResult.getLastLocation().getLatitude(), locationResult.getLastLocation().getLongitude()),
                                        (key, error) -> {
                                            if (error != null){
                                                Toast.makeText(HomeActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                                            }
                                            else {
                                                Toast.makeText(HomeActivity.this, "You are online", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            }
                        };
                        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(HomeActivity.this);
                        mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
                    }
                } else {
                    Toast.makeText(HomeActivity.this, "Unable to get location", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

But nothing is showing in firebase database.

Rules of firebase database:

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": "auth!=null",
    ".write": "auth!=null"
  }
}

map is showing properly but when I open the activity my current location is not uploading.I want to upload my current location when I open the activity.And location in database of current users will removed when activity will be destroyed.

question from:https://stackoverflow.com/questions/65918261/not-able-to-upload-geofire-location-in-firebase-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I solved the issue. We have to set the location in geofire when the lastKnownLocation is not equal to null in the if condition.

private void getDeviceLocation() {
        mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                    mLastKnownLocation = task.getResult();
                    if (mLastKnownLocation != null) {
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(),
                                mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                        geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(),
                                new GeoLocation(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()),
                                (key, error) -> {
                                    if (error != null){
                                        Toast.makeText(HomeActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                    else {
                                        Toast.makeText(HomeActivity.this, "You are online", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    } else {
                        locationRequest = new LocationRequest();
                        locationRequest.setInterval(10000);
                        locationRequest.setFastestInterval(5000);
                        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                        locationCallback = new LocationCallback() {
                            @Override
                            public void onLocationResult(LocationResult locationResult) {
                                super.onLocationResult(locationResult);
                                LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),locationResult.getLastLocation().getLongitude());
                                mLastKnownLocation = locationResult.getLastLocation();
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition, DEFAULT_ZOOM));
                                //mFusedLocationProviderClient.removeLocationUpdates(locationCallback);

                                geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(),
                                        new GeoLocation(locationResult.getLastLocation().getLatitude(), locationResult.getLastLocation().getLongitude()),
                                        (key, error) -> {
                                            if (error != null){
                                                Toast.makeText(HomeActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                                            }
                                            else {
                                                Toast.makeText(HomeActivity.this, "You are online", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            }
                        };
                        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(HomeActivity.this);
                        mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
                    }
                } else {
                    Toast.makeText(HomeActivity.this, "Unable to get location", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...