GeoQuery 和 GeoFire 监听器冲突导致随机结果

GeoQuery and GeoFire listeners clashing resulting in random results

简而言之,我正在开发一个应用程序,旨在获取当前用户的最后一个已知位置并显示附近的用户(半径30公里以内)Swipe Cards.我正在使用 FireBaseGeoFire 来完成这个。在实现位置查询之前,我只使用

onChildAdded()

侦听器从数据库中获取所有用户 - 它工作正常。

但是,当我添加使用另一组侦听器的位置查询时,我开始得到随机和意外的结果。例如重复 - 它会获取所有用户两次,然后将它们显示在两张后续卡片上,即我会第一次刷用户 A,然后同一用户会再次出现在下一张卡片上。更令人困惑的是,这只是有时发生。我是 GeoFire 的新手,但是 我怀疑听众之间存在某种冲突

这是我的代码:

1) 在 onCreate() 中,我检查位置权限。随后,我每两分钟使用 FusedLocationProviderClient 请求位置更新。一切正常,符合预期。

2) 每两分钟,我收到当前位置并触发此 onLocationResult() 回调:

// location callback - get location updates here:
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        Log.d("MainActivity", "onLocationResult triggered!");
        for(Location location : locationResult.getLocations()) {
            mCurrentLocation = location;
            Log.d("MainActivity", "Lat: " + mCurrentLocation.getLatitude() + ", Long: " + mCurrentLocation.getLongitude());
            // write current location to geofire:
            mGeofireDB = FirebaseDatabase.getInstance().getReference("Locations");
            GeoFire geofire = new GeoFire(mGeofireDB);
            geofire.setLocation(mCurrentUserID, new GeoLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), new GeoFire.CompletionListener() {
                @Override
                public void onComplete(String key, DatabaseError error) {
                    if (error != null) {
                        Log.d("MainActivity", "There was an error saving the location to GeoFire: " + error);
                    } else {
                        Log.d("MainActivity", "Location saved on server successfully!");
                        // check current user sex:
                        checkSex();

                        // find nearby users of the current user's location:
                        getNearbyUsers();
                       // here's rest of the code which takes the list of cards created by getNearbyUsers() and displays those cards

3) 成功将位置写入数据库后,我将调用 checkSex() 方法,该方法不言自明并且工作正常。然后,我试图在下面的函数中使用 GeoQuery 获取附近的用户。

// get all nearby users:
private void getNearbyUsers() {
    Log.d("MainActivity", "getNearbyUsers() triggered!");
    mLocationsDB = FirebaseDatabase.getInstance().getReference().child("Locations");
    GeoFire geoFire = new GeoFire(mLocationsDB);
    GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), mCurrentUserProximityRadius);
    geoQuery.removeAllListeners();
    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
        // user has been found within the radius:
        @Override
        public void onKeyEntered(String key, GeoLocation location) {
            Log.d("MainActivity", "User " + key + " just entered the radius. Going to display it as a potential match!");
            nearbyUsersList.add(key);
        }

        @Override
        public void onKeyExited(String key) {
            Log.d("MainActivity", "User " + key + " just exited the radius.");

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mCardList.removeIf(obj -> obj.getUserID().equals(key));
                mCardArrayAdapter.notifyDataSetChanged();
                Log.d("MainActivity", "User " + key + " removed from the list.");
            } else {
                Log.d("MainActivity", "User should have exited the radius but didn't! TODO support older versions of Android!");
            }
        }

        @Override
        public void onKeyMoved(String key, GeoLocation location) {

        }

        // all users within the radius have been identified:
        @Override
        public void onGeoQueryReady() {
            displayPotentialMatches();
        }

        @Override
        public void onGeoQueryError(DatabaseError error) {

        }
    });
}
// end of getNearbyUsers()

我检索半径内的所有用户 (onKeyEntered()) 并将它们添加到 nearbyUsersList。一旦找到所有用户并将其添加到列表中(又一个侦听器 - onGeoQueryReady()),我最终调用 displayPotentialMatches() 方法,我在其中检查数据库中的用户是否在 nearbyUsersList 中,如果是,我将它们添加到mCardList 并通知适配器有关更改:

// retrieve users from database and display them on cards, based on the location and various filters:
private void displayPotentialMatches() {
    Log.d("MainActivity", "displayPotentialMatches() triggered!");
    mUsersDB.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Log.d("MainActivity", "displayPotentialMatches ON CHILD ADDED listener triggered!");
            // check if there is any new potential match and if the current user hasn't swiped with them yet:
            if (dataSnapshot.child("Sex").getValue() != null) {
                if (dataSnapshot.exists()
                        && !dataSnapshot.child("Connections").child("NoMatch").hasChild(mCurrentUserID)
                        && !dataSnapshot.child("Connections").child("YesMatch").hasChild(mCurrentUserID)
                        && !dataSnapshot.getKey().equals(mCurrentUserID)
                        // TODO display users based on current user sex preference:
                        && dataSnapshot.child("Sex").getValue().toString().equals(mCurrentUserOppositeSex)
                        // location check:
                        && nearbyUsersList.contains(dataSnapshot.getKey())
                        ) {
                    String profilePictureURL = "default";
                    if (!dataSnapshot.child("ProfilePictureURL").getValue().equals("default")) {
                        profilePictureURL = dataSnapshot.child("ProfilePictureURL").getValue().toString();
                    }
                    // POPULATE THE CARD WITH THE DATABASE INFO:
                    Log.d("MainActivity", dataSnapshot.getKey() + " passed all the match checks!");
                    Card potentialMatch = new Card(dataSnapshot.getKey(), dataSnapshot.child("Name").getValue().toString(), profilePictureURL);
                    mCardList.add(potentialMatch);
                    mCardArrayAdapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
} // end of displayPotentialMatches()

此代码后跟一段代码,该代码获取该列表并将这些用户显示在卡片上。这段代码在我实施 GeoQuerying 之前已经过测试并且运行良好,因此我不在此处包含它。还在定位结果回调中

我很确定,如果我不需要使用那么多侦听器(onKeyEntered、onGeoQueryReady、onChildAdded),它会按预期工作。我会在 onGeoQueryReady 侦听器中从数据库中获取所有数据,一旦准备就绪,就会执行在卡片上显示用户的代码。

但是,由于即使在从 FireBase 获取数据时也需要使用侦听器 - onChildAdded(我知道 - 它是实时的),因此会导致意外 results/duplicates。有时它会起作用,有时我会像上面提到的那样重复(连续两张卡上的同一用户)。但是 notifyDataSetChanged 仅在 onChildAdded 侦听器中调用。

我在这里错过了什么?听众是否以某种方式发生冲突(例如,一个被调用然后另一个没有完成第一个)?或者是在没有完成所有侦听器的情况下调用在卡片上显示用户的代码段,因此 onGeoQueryReady 和 onChildAdded 都会触发它?如果是这种情况,有没有办法只在两个侦听器都完成后才执行这段代码?

如果您还需要什么,请告诉我,例如日志的屏幕截图。任何帮助将非常感激。

首先,当位置发生变化时,您不需要总是初始化 geofire 实例。其次,不要等待监听器中的地理查询准备就绪。

将这些变量设为 class 级别:

mGeofireDB = FirebaseDatabase.getInstance().getReference("Locations");
mUsersDB = FirebaseDatabase.getInstance().getReference("users");
GeoFire geofire = new GeoFire(mGeofireDB);
GeoQuery geoQueryNearByUser=null;

GeoQueryEventListener geoQueryEventListener=new GeoQueryEventListener() {
    // user has been found within the radius:
    @Override
    public void onKeyEntered(String key, GeoLocation location) {
        Log.d("MainActivity", "User " + key + " just entered the radius. Going to display it as a potential match!");
        nearbyUsersList.add(key);
        mUsersDB.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){
                    if (dataSnapshot.child("Sex").getValue() != null) {
                        if (dataSnapshot.exists()
                                && !dataSnapshot.child("Connections").child("NoMatch").hasChild(mCurrentUserID)
                                && !dataSnapshot.child("Connections").child("YesMatch").hasChild(mCurrentUserID)
                                && !dataSnapshot.getKey().equals(mCurrentUserID)
                                // TODO display users based on current user sex preference:
                                && dataSnapshot.child("Sex").getValue().toString().equals(mCurrentUserOppositeSex)
                                // location check:
                                && nearbyUsersList.contains(dataSnapshot.getKey())
                                ) {
                            String profilePictureURL = "default";
                            if (!dataSnapshot.child("ProfilePictureURL").getValue().equals("default")) {
                                profilePictureURL = dataSnapshot.child("ProfilePictureURL").getValue().toString();
                            }
                            // POPULATE THE CARD WITH THE DATABASE INFO:
                            Log.d("MainActivity", dataSnapshot.getKey() + " passed all the match checks!");
                            Card potentialMatch = new Card(dataSnapshot.getKey(), dataSnapshot.child("Name").getValue().toString(), profilePictureURL);
                            mCardList.add(potentialMatch);
                            mCardArrayAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    @Override
    public void onKeyExited(String key) {
        Log.d("MainActivity", "User " + key + " just exited the radius.");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mCardList.removeIf(obj -> obj.getUserID().equals(key));
            mCardArrayAdapter.notifyDataSetChanged();
            Log.d("MainActivity", "User " + key + " removed from the list.");
        } else {
            Log.d("MainActivity", "User should have exited the radius but didn't! TODO support older versions of Android!");
        }
    }

    @Override
    public void onKeyMoved(String key, GeoLocation location) {

    }

    // all users within the radius have been identified:
    @Override
    public void onGeoQueryReady() {
    }

    @Override
    public void onGeoQueryError(DatabaseError error) {

    }
};

我更改了上面的地理查询,以便在用户密钥可用时立即获取该特定用户数据并将卡添加到适配器。

定位回调:

在位置回调中只使用最后一个位置循环位置数组将导致异常,因为您同时触发多个地理查询侦听器

    // location callback - get location updates here:
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        Log.d("MainActivity", "onLocationResult triggered!");

            mCurrentLocation = locationResult.getLastLocation();
            Log.d("MainActivity", "Lat: " + mCurrentLocation.getLatitude() + ", Long: " + mCurrentLocation.getLongitude());
            // write current location to geofire:
            geofire.setLocation(mCurrentUserID, new GeoLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), new GeoFire.CompletionListener() {
                @Override
                public void onComplete(String key, DatabaseError error) {
                    if (error != null) {
                        Log.d("MainActivity", "There was an error saving the location to GeoFire: " + error);
                    } else {
                        Log.d("MainActivity", "Location saved on server successfully!");
                        // check current user sex:
                        checkSex();

                        // find nearby users of the current user's location:
                        getNearbyUsers();
                    }
                }
            }

    }
};

我们检查查询实例是否存在,而不是再次初始化查询,而只是用用户的当前位置更新查询的中心。

// get all nearby users:
private void getNearbyUsers() {
    Log.d("MainActivity", "getNearbyUsers() triggered!");

    GeoLocation currentLocationGeoHash = new GeoLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
    if(geoQueryNearByUser == null){
        geoQueryNearByUser = geoFire.queryAtLocation(currentLocationGeoHash, mCurrentUserProximityRadius);

        geoQueryNearByUser.addGeoQueryEventListener(geoQueryEventListener);
    }
    else {
        geoQueryNearByUser.setCenter(currentLocationGeoHash);
    }

}
// end of getNearbyUsers()