2016-05-21 62 views
0

所以我有我的后端使用firebase。我打算做的是将用户匹配添加到用户ID。但是,当用户最初报名时,他们没有匹配。我想要做的是检查用户孩子中是否存在“匹配”子元素,如果不是,则创建列表子元素并存储第一个匹配元素。但是,如果它已经存在,则只需添加比赛。这里是我的代码:firebase检查是否存在小孩

public void setMatch(final String match){ 
    final Firebase ref = new Firebase("FIREBASEURL"); 
    final Firebase userRef = ref.child("Flights").child(userName); 
    userRef.addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      System.out.println("does the child exist? " + dataSnapshot.child("matches").exists()); 
      if(!dataSnapshot.child("matches").exists()){ 
       ArrayList<String> matches = new ArrayList<String>(); 
       matches.add(match); 
       Firebase matchesRef = userRef.child("matches"); 
       matchesRef.setValue(matches); 
       userRef.removeEventListener(this); 
      }else if(dataSnapshot.child("matches").exists()){ 
       Map<String, Object> matches = new HashMap<>(); 
       matches.put("matches", match); 
       userRef.child("matches").push().setValue(matches); 
       userRef.removeEventListener(this); 
      } 
     } 

     @Override 
     public void onCancelled(FirebaseError firebaseError) { 

     } 
    }); 
} 

目前,正在添加值的两倍(在else如果被调用两次,如果该领域已经存在,/它称为如果它不)。我不确定我做错了什么。

回答

1

这听起来相当过于复杂。在Firebase数据库中,最好尽可能分开读写操作。虽然push id是以时间顺序存储数据的好方法,如果项目具有自然键,通常最好将它们存储在该键下。

例如,如果您的String match确实是String matchId,则可以通过使用matchId作为关键字确保每个匹配最多存在一次。

userRef.child("matches").child(matchId).setValue(true); 

此操作幂等:它会产生相同的结果,无论多久你运行它。

你会注意到,我不检查的matches已经存在:在火力地堡数据库自动生成所需要存储的值的所有节点,它会自动删除了下面有没有值的所有节点。

1

它看起来像你创建的字段,如果它不存在于if块中,然后测试以查看该字段(刚刚创建的)是否存在,现在它确实存在,因此它再次添加它。 removeEventListener调用将删除侦听器,但不会停止当前代码的完成。

尝试:

if(!dataSnapshot.child("matches").exists()){ 
      ArrayList<String> matches = new ArrayList<String>(); 
      matches.add(match); 
      Firebase matchesRef = userRef.child("matches"); 
      matchesRef.setValue(matches); 
      userRef.removeEventListener(this); 
      return; 
     }else if(dataSnapshot.child("matches").exists()){ 
      Map<String, Object> matches = new HashMap<>(); 
      matches.put("matches", match); 
      userRef.child("matches").push().setValue(matches); 
      userRef.removeEventListener(this); 
     } 

添加return语句应相当当前通话,并且还禁止监听器,你打算。

相关问题