在firebase android中检索数据时卡住了

时间:2017-09-05 19:56:32

标签: android database firebase firebase-realtime-database

在运行时,我总是卡在这里:databaseRefer.addValueEventListener(new ValueEventListener()我尝试了不同的方法,但结果相同。

我正在尝试读取该节点以检查该用户名是否已存在。

public void validateUsername(final String sUsername, final FirebaseUser user) {

    DatabaseReference databaseRefer;
    FirebaseDatabase mFirebaseInstance;

    mFirebaseInstance = FirebaseDatabase.getInstance();

    databaseRefer = mFirebaseInstance.getReference().child("TakenUserNames").child(sUsername);
    databaseRefer.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                // username is already taken
                Toast.makeText(SignupActivity.this, "Username already exist. try a different one", Toast.LENGTH_SHORT).show();
            } else {
                // username is valid
                onAuthenticationSucess(user);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(SignupActivity.this, "Connection Error. Please try again in some time.", Toast.LENGTH_SHORT).show();
        }
    });
}

enter image description here

1 个答案:

答案 0 :(得分:2)

尝试以下代码

public void validateUsername(final String sUsername) {
        DatabaseReference databaseRefer;
        FirebaseDatabase mFirebaseInstance;

        mFirebaseInstance = FirebaseDatabase.getInstance();

        databaseRefer = mFirebaseInstance.getReference().child("TakenUserNames").child(sUsername);
        databaseRefer.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                    // username is already taken
                    Toast.makeText(SignupActivity.this, "Username already exist. try a different one", Toast.LENGTH_SHORT).show();
                } else {
                    // username is valid
                    onAuthenticationSucess(task.getResult().getUser());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(SignupActivity.this, "Connection Error. Please try again in some time.", Toast.LENGTH_SHORT).show();
            }
        });
    }

注意: - 当您调用Firebase API时,该API将在单独的线程上运行。因此,在Firebase调用之后的函数中,您将从布尔数组返回值。但Firebase API调用尚未完成。因此,尝试执行或在onDataChange()中运行代码。