- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
简而言之,我正在开发一个应用程序,旨在获取当前用户的最后已知位置并显示附近的用户(30 公里半径内)Swipe Cards .我正在使用 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()) 并将它们添加到 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(我知道 - 它是实时的),因此会导致意外结果/重复。有时它会起作用,有时我会像上面提到的那样重复(连续两张卡上的同一用户)。但是 notifyDataSetChanged 仅在 onChildAdded 监听器中调用。
我在这里错过了什么?听众是否以某种方式发生冲突(例如,一个被调用然后另一个没有完成第一个)?或者是在没有完成所有监听器的情况下调用在卡片上显示用户的代码段,因此 onGeoQueryReady 和 onChildAdded 都会触发它?如果是这种情况,有没有办法只在两个监听器都完成后才执行这段代码?
如果您需要其他任何东西,请告诉我,例如日志的屏幕截图。任何帮助将非常感激。
最佳答案
首先,当位置发生变化时,您不需要总是初始化 geofire 实例。其次,不要等待监听器中的地理查询准备就绪。
使这些变量类级别:
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) {
}
};
我更改了上面的地理查询,以便在用户 key 可用时立即获取该特定用户数据并将卡添加到适配器。
位置回调:
在位置回调只使用最后一个位置。 循环位置数组将导致异常,因为您同时触发多个地理查询监听器
// 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()
关于java - GeoQuery 和 GeoFire 监听器冲突导致随机结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49369449/
我的工作是将每条记录写入 Hadoop 映射中的 DynamoDB。 我无法使用具有 httpclient-4.2.5.jar 和 httpcore-4.2.5.jar 的 Hadoop 2.6 运行
我在 JavaScript 中嵌套了循环开关,例如: for (var i = 0; i < checkBoxIds.length; i++) { if ($('#' + checkB
我有一个文件夹被重命名的分支。现在我正在尝试合并从主干到这个分支的更改,但是在主干中修改的文件仍然在原始文件夹名称下,因此 svn 引发了树冲突。我该如何解决这个问题? 该文件夹已使用 svn ren
我在使用 jquery 暴露插件和 Masked 输入插件时遇到了问题。问题是它们都占用 $.mask 函数,从而导致冲突。但我非常需要这两个插件一起工作。我会将其中一个中的 $.mask 重命名为.
我正在尝试为我所有的 INPUT 元素做一个简单的 :focus 效果,就像这样: INPUT:focus { border-color: orange; } 这很好用,直到我将这段 CSS 添加到样
我是 javascript 的新手。 在 wordpress 上工作,我在自定义 js 中为我的主题输入了以下函数: document.getElementsByName("empty_cart")[
为什么有些 javascript 会与其他的发生冲突?我的意思是我一直在为图片库使用 javascript 代码,然后尝试在 jquery 中获取文本水印。为什么在使用 jquery 之后,画廊完全消
是否可以根据已知的输入值创建 MD5 碰撞? 所以例如我有输入字符串 abc与 MD5 900150983cd24fb0d6963f7d28e17f72 . 现在我想将字节添加到字符串 def获得相同
我在我的项目中使用原型(prototype): NodeParser.prototype.getChildren = function(parentContainer) { return fl
根据我对 merge 冲突的理解,当两个人更改了同一文件和/或修改了该文件中的同一行时,就会发生 merge 冲突。所以当我做一个 git pull origin master 我期望 merge 冲
iPad 上 Mobile Safari 中的 HTML5 模板。带 iScroll 的 Div 工作正常。 if/else 语句中还包含一个 jQuery 函数。该函数测试用户是否在 iScroll
我一直在尝试使 2 个脚本(1 个 mootol 和 1 个 jquery)在同一页面上工作,但没有成功。我一直在研究许多论坛等,但我仍然无法使这两个脚本同时工作。 这就是它在我的标题中的样子: /w
我想克隆带标题的问号。一切正常,但是当我将鼠标悬停在新问号上时,第一个问号上会出现工具提示。有什么想法吗? 我正在使用 jQuery 和醉酒的工具提示。 Demo here click here
好吧,我已经在一个 friend 的网站上工作了一段时间了。我的编码技能......值得怀疑,而且我遇到了很多问题。 目前我网站上的 jQuery 停止工作了,我找不到原因,并且我已尽一切努力让它工作
我想使用一个文件来保存所有#define 和常量:示例 #ifndef CONSTANTS_H_ #define CONSTANTS_H_ #include //OVERALL DEFS
我在我的表单中的所有 HTML 下都有一些验证码,这似乎阻止了我的复选框验证码的工作,一旦我在我的 HTML 下的代码周围添加/* */(使其不活动),我就得出了这个结论) 复选框验证代码开始正常工作
我是新手。我的页面上有两个 javascript/jquery。如果我使用第一个脚本,第二个脚本将不起作用。如果我删除第一个脚本,第二个脚本就可以正常工作。我不知道如何解决这个问题。我知道有一个“无冲
我是 Bison 新手,在处理 Shift/Reduce 冲突时遇到了麻烦... 我正在为C语言编写语法规则:ID是标识变量的标记,我编写此规则是为了确保即使将标识符写在括号中,也可以考虑它。 id
我目前正在使用 LibGdx 开发我的第一个 Android 游戏项目。这是一款 2D 迷宫游戏,您可以使用触摸输入从其中一个入口到其中一个导出“画出”一条线。世界本身是一个 TiledMap,目前仅
我正在尝试通过 javascript 完成表单验证,并在 #form# 标记中放置一个要执行的 .py 文件操作。但问题是,当我提交数据后,它不会重定向到 .py 操作。所以我摆脱了 preventd
我是一名优秀的程序员,十分优秀!