【发布时间】:2018-03-19 17:54:24
【问题描述】:
简而言之,我正在开发一个应用程序,该应用程序旨在获取当前用户的最后一个已知位置,并在Swipe Cards 上显示附近的用户(半径 30 公里内)。我正在使用 FireBase 和 GeoFire 来完成此任务。在我实现位置查询之前,我只使用了
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()) 并将它们添加到附近的用户列表中。一旦找到所有用户并将其添加到列表中(又一个侦听器 - onGeoQueryReady()),我最后调用 displayPotentialMatches() 方法,在其中检查数据库中的用户是否在附近的用户列表中,如果是,我将它们添加到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(我明白了 - 它是实时的),您也需要使用侦听器,因此会导致意外结果/重复。有时它可以工作,有时我会得到重复(连续两张卡上的同一用户),如上所述。但是 notifyDataSetChanged 只在 onChildAdded 监听器中被调用。
我在这里缺少什么?听众是否以某种方式发生冲突(例如,一个被调用,然后另一个没有完成)?或者是在没有完成所有侦听器的情况下在卡片上显示用户的代码段,因此 onGeoQueryReady 和 onChildAdded 都会触发它?如果是这种情况,有没有办法只在两个侦听器都完成后才执行这段代码?
如果您需要其他任何东西,请告诉我,例如日志的屏幕截图。任何帮助将非常感激。
【问题讨论】:
-
您有一个竞争条件 - 发出 geofire.setLocation 时,前一个侦听器仍被注册,然后在 getNearbyusers 中删除 - 因此有可能在调用下一个查询之前调用前一个侦听器。
-
@Andy 所以我不应该删除那些听众吗?
-
最简单的事情似乎是拥有一个 GeoQuery 实例(不要每次都在 getNearbyUsers 中重新创建)并在新位置使用 geoQuery.setCenter,现在您不必删除所有侦听器(始终只有一个查询和侦听器 - 因此您的 geoQuery 现在是一个创建一次的类级变量(如果为 null)。
标签: java android geolocation listener geofire