我正在尝试在检查匹配的几个值并将我的数据插入这些对象后在firebase中插入数据。但是在数据插入之前它很有效,因为数据插入代码在firebase实时数据库启动时执行主UI线程暂停和无限插入。
这是代码:
final Schedule schedule = new Schedule(latestCalendar.getTimeInMillis(),String.valueOf(hourOfDay)+":"+String.valueOf(minute)+" - "+String.valueOf(hourOfDayEnd)+":"+String.valueOf(minuteEnd));
final HashMap<String, Object> teamMap = (HashMap<String, Object>) new ObjectMapper().convertValue(schedule, Map.class);
AppBaseActivity.firebaseDatabase.getReference().child("Users").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
final UserModel user = postSnapshot.getValue(UserModel.class);
AppBaseActivity.firebaseDatabase.getReference().child("Users").child(user.getUid()).child("Teams").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
final Team myTeam = postSnapshot.getValue(Team.class);
if (teamID.equals(myTeam.getTid())) {
final String tid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
// It goes infinite on this code
AppBaseActivity.firebaseDatabase.getReference().child("Users").child(user.getUid()).child("Teams").child(myTeam.getTid()).child("Schedule").child(tid).setValue(teamMap);
}
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Toast.makeText(ScheduleTeam.this, getString(R.string.cancel), Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Toast.makeText(ScheduleTeam.this,getString(R.string.cancel),Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:2)
您的代码看起来过于复杂。请注意,将监听器附加到/Users
会将所有用户读入您的Android应用。如果您只是在寻找一个特定的用户,那么加载所有这些用户就会浪费Android设备的大量带宽和处理能力。通过使用查询,您最好只加载您需要的用户:
DatabaseReference users =
AppBaseActivity.firebaseDatabase.getReference().child("Users");
Query userQuery = users.orderByChild("tid").equalTo(teamID);
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
final UserModel user = postSnapshot.getValue(UserModel.class);
for (DataSnapshot teamSnapshot: postSnapshot.child("Teams")
final Team myTeam = teamSnapshot.getValue(Team.class);
if (teamID.equals(myTeam.getTid())) {
final String tid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
teamSnapshot.getRef().child("Schedule").child(tid).setValue(teamMap);
}
});
}
}
@Override
public void onCancelled(DatabaseError error) {
Toast.makeText(ScheduleTeam.this,getString(R.string.cancel),Toast.LENGTH_SHORT).show();
}
一些变化:
tid
等于teamID
值的用户。Schedule
的路径,而不是从根目录重构它。据我所知,此代码与您的代码相同。但那里有一点点,所以可能会有一些小错误。一般来说,我建议您尝试理解上面描述的3个更改,因为它们可能比复制/粘贴代码更有帮助。