6

I have a firebase that has a node called users. The user gives a username and I want to check to see if that username already exists as a child of the users node. This is the code I am currently trying. The platform is android.

String myUsername = userNameInputET.getText().toString();
if(mUsersRef.child(myUsername) == null) {
//do stuff
} else {
//do other stuff
}

This code is not working, it always goes to the else, even if the child with the given username does not exist. What to do?

4

4 回答 4

0
    String myUsername="User";

    if (root.child(myUsername).getRoot() == null) {

    } else {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", "");
        root.updateChildren(map);    
于 2016-09-21T08:18:40.277 回答
0

你好检查这个https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot

// Test for the existence of certain keys within a DataSnapshot
var ref = firebase.database().ref("users/ada");
ref.once("value")
  .then(function(snapshot) {
    var a = snapshot.exists();  // true
    var b = snapshot.child("name").exists(); // true
    var c = snapshot.child("name/first").exists(); // true
    var d = snapshot.child("name/middle").exists(); // false
  });
于 2016-10-19T11:04:39.617 回答
0

在这个问题上浪费了两个小时。尝试了一切,但没有一个解决方案有效。我使用 firebase onChildAdded 的数据读取代码来获取用户数据,然后使用 if else 条件确定它。

在 onCreate

mFirebaseDatabase=FirebaseDatabase.getInstance();
mMessagesDatabaseReference=mFirebaseDatabase.getReference().child("user").child(root).child(id);
    attachDatabaseReadListener();

监听器方法

    private void attachDatabaseReadListener() {
    if ( mChildEventListener == null) {
        mChildEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                User u = dataSnapshot.getValue(User.class);
                mUser=u.GetUser();
                mEmail=u.GetEmailId();
                Toast.makeText(getApplicationContext(),"here"+mUser,Toast.LENGTH_SHORT).show();
            }
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
            public void onChildRemoved(DataSnapshot dataSnapshot) {}
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
            public void onCancelled(DatabaseError databaseError) {}
        };
        mMessagesDatabaseReference.addChildEventListener( mChildEventListener);

    }
}

条件检查,它可以是任何东西。

 if(mUser==null&&mEmail==null) {
      //do something here
  }
 else
 {
 //do nothing
 }

注意:在添加的子节点上执行需要一些时间,所以添加适当的延迟 我只有一个节点,所以这段代码对我来说非常有效。如果有任何其他解决方案或更简单的解决方案可用,请告诉我。

如果根节点不存在,那么它也会显示为 null,因此在部署应用程序推送根节点之前请记住这一点。

于 2017-03-17T15:28:49.640 回答
-3

我相信您需要将代码更改为

String myUsername = userNameInputET.getText().toString();
if(mUsersRef.child(myUsername).getValue() == null) {
   //do stuff
} else {
   //do other stuff
}
于 2016-05-20T17:57:06.250 回答