Как получить все остальные пользовательские ключи, введенные в мой запрос - PullRequest
0 голосов
/ 05 апреля 2020

enter image description here

Вот структура базы данных Firebase. В этой БД я сохранил все местоположение пользователя, используя GeoFire под ключом пользователя. Когда я пытаюсь получить все другие пользовательские ключи, которые вводятся в текущее местоположение пользовательского запроса с радиусом 1 км, тогда это просто показывает один пользовательский ключ. Но все широта и долгота местоположения пользователя такие же, как и у местоположения запроса.

Мой код указан ниже. Пожалуйста, помогите мне найти решение, в котором я ошибся. Я пытаюсь так много раз на inte rnet или Google. Я ничего не делал. Я также новичок в Geofire ... Так что я ищу решение заранее спасибо.

package com.example.mychatapp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryDataEventListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class SafeActivity extends AppCompatActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener {

    GoogleApiClient googleApiClient;
    LocationRequest locationRequest;
    Location lastLocation;
    private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;
    private int radius = 1;
    private boolean userLogoutStatus = false, OtherUserFound = false;


    private FirebaseAuth mAuth;
    private DatabaseReference currentUserGeoFire;

    private Toolbar mToolbar;
    private Button HelpButton, CancelButton;
    private String currentUserID, OtherUserFoundID;

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

        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        currentUserGeoFire = FirebaseDatabase.getInstance().getReference().child("GeoFire");


        initializedField();
        buildGoogleApiClient();


    }



    private void initializedField() {
        mToolbar = findViewById(R.id.main_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Help Me");

        HelpButton = findViewById(R.id.help_button);
        CancelButton = findViewById(R.id.cancel_button);

        HelpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getOtherClosetUser();
            }
        });

        CancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GeoFire geoFire = new GeoFire(currentUserGeoFire);
                geoFire.removeLocation(currentUserID);
                DisconnectLocation();
            }
        });
    }


    private void DisconnectLocation() {

        currentUserGeoFire.child(currentUserID).removeValue();
    }


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

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(SafeActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_CODE_LOCATION_PERMISSION);
        }

        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

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

        DatabaseReference CurrentUserLocation = FirebaseDatabase.getInstance().getReference().child("GeoFire");

        GeoFire CurrentUserGeoFire = new GeoFire(CurrentUserLocation);
        CurrentUserGeoFire.setLocation(currentUserID, new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()), new GeoFire.CompletionListener() {
            @Override
            public void onComplete(String key, DatabaseError error) {
                if (error != null) {
                    Toast.makeText(SafeActivity.this, "There was an error saving the location to GeoFire: " + error, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(SafeActivity.this, "Location saved on server successfully!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getOtherClosetUser() {
        final ArrayList<String> runnersNearby = new ArrayList<>();
        final DatabaseReference otherUserRef = FirebaseDatabase.getInstance().getReference().child("User");
        GeoFire geoFire = new GeoFire(otherUserRef);
        GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(lastLocation.getLatitude(),lastLocation.getLongitude()), radius);
        geoQuery.removeAllListeners();

        geoQuery.addGeoQueryDataEventListener(new GeoQueryDataEventListener() {
            @Override
            public void onDataEntered(DataSnapshot dataSnapshot, GeoLocation location) {
                if (dataSnapshot.exists()) {
                    if (currentUserID!=dataSnapshot.getKey()){
                        OtherUserFound = true;
                        runnersNearby.add(dataSnapshot.getKey());
                    }
                }
            }

            @Override
            public void onDataExited(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onDataMoved(DataSnapshot dataSnapshot, GeoLocation location) {

            }

            @Override
            public void onDataChanged(DataSnapshot dataSnapshot, GeoLocation location) {

            }

            @Override
            public void onGeoQueryReady() {

            }

            @Override
            public void onGeoQueryError(DatabaseError error) {

            }
        });
    }


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