从Firebase中检索数据,Firebase是根节点子节点的子节点

时间:2017-05-03 18:27:08

标签: android firebase login firebase-realtime-database

我想在登录屏幕上匹配ID和密码,ID是根节点的子节点,密码和其他子节点作为子节点。但是我的代码使活动行为不当而不执行任务。Database Structure  代码如下:

    private void login(){
    final String id1 = id.getText().toString().trim();
    final String pwd1 = password.getText().toString().trim();
    if (TextUtils.isEmpty(id1)){
        Toast.makeText(this, "Enter ID", Toast.LENGTH_SHORT).show();
        return;
    }
    if (TextUtils.isEmpty(pwd1)){
        Toast.makeText(this, "Enter Password", Toast.LENGTH_SHORT).show();
        return;
    }
    final ProgressDialog progressDialog = new ProgressDialog(User_Login.this);
    progressDialog.setMessage("Logging in..");
    progressDialog.show();

    databaseReference= FirebaseDatabase.getInstance().getReference().child("user");
    DatabaseReference databaseReference1=databaseReference.child(id1);
    databaseReference1.child(pwd1).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(pwd1.equals(dataSnapshot.child("password").getValue().toString())){
                progressDialog.dismiss();
                finish();
                Toast.makeText(User_Login.this, "Login Successful", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(User_Login.this,Services.class));
            }
            else{
                progressDialog.dismiss();
                Toast.makeText(User_Login.this, "Wrong Id/Password", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

1 个答案:

答案 0 :(得分:0)

请使用此代码:

databaseReference = FirebaseDatabase.getInstance().getReference().child("user").child(id1);
databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(pwd1.equals(dataSnapshot.child("password").getValue().toString())){
            progressDialog.dismiss();
            finish();
            Toast.makeText(User_Login.this, "Login Successful", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(User_Login.this,Services.class));
        } else {
            progressDialog.dismiss();
            Toast.makeText(User_Login.this, "Wrong Id/Password", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

问题是您要添加一个额外的孩子child(pwd1),这是不必要的。

希望它有所帮助。