Firebase android : make username unique

前端 未结 3 1540
不思量自难忘°
不思量自难忘° 2020-11-21 22:43

Parse will shut down at the end of the year, so I decided to start using Firebase. I need to implement a register process with 3 fields : email, username, password (

3条回答
  •  星月不相逢
    2020-11-21 23:21

    Save usernames as suggested by Frank but when you save usernames, use runTransaction function in Firebase to make sure that the username is not taken. This function is guaranteed by Firebase to be an atomic operation so you can be rest assured of no collision

    firebaseRef.child("usernames").child(username).runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            if (mutableData.getValue() == null) {
                mutableData.setValue(authData.getUid());
                return Transaction.success(mutableData);
            }
    
            return Transaction.abort();
        }
    
        @Override
        public void onComplete(FirebaseError firebaseError, boolean commited, DataSnapshot dataSnapshot) {
            if (commited) {
                // username saved
            } else {
                // username exists
            }
        }
    });
    

提交回复
热议问题