在Firebase Android中,检索子节点的值并将其保存在布尔变量中

时间:2017-10-20 12:32:43

标签: android firebase firebase-realtime-database

I want to retrieve the value of admin and check if its true or false.

我的代码:

final Boolean[] ifadmin = new Boolean[1];
DatabaseReference admin=mFirebaseuser.child(auth.getCurrentUser().getUid()).child("admin");
admin.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        System.out.print("ifadmin"+ ifadmin[0]);
        ifadmin[0] = (boolean) dataSnapshot.getValue();
        System.out.print("ifadmin"+ ifadmin[0]);
        // do your stuff here with value

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

if(ifadmin[0]){
    Intent intent = new Intent(LoginActivity.this, AdminActivity.class);
    System.out.println("uid1 "+auth.getCurrentUser().getUid());
    startActivity(intent);
    finish();
}

理想情况下,我应该对if(ifadmin[0])得到真或假,但我得到一个空指针异常。

我是Android和Firebase的新手,请帮我解决此错误。

1 个答案:

答案 0 :(得分:0)

要获取布尔管理员归档的值,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(auth.getCurrentUser().getUid());
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        boolean admin = dataSnapshot.child("admin").getValue(Boolean.class);
        Log.d("TAG", admin);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);

输出应为:true