如何在firebase数据库中没有电子邮件val时显示错误消息

时间:2017-02-13 07:54:38

标签: android firebase firebase-realtime-database

我的Firebase数据库如下所示:

enter image description here

我想在firebase数据库中没有电子邮件val时显示错误消息。

我的代码是

mRef.orderByChild("email").equalTo(val).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            User user = dataSnapshot.getValue(User.class);

                textView.setText("Welcome " + user.name );
                System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                User user = dataSnapshot.getValue(User.class);
                textView.setText("Welcome " + user.name );
                System.out.println(user.name + "\n" + user.email + "\n" + user.tell);

        }



        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {


        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

2 个答案:

答案 0 :(得分:1)

ChildEventListener只能检测某个子节点是否存在,或者是否更改/删除子节点。它无法检测到孩子的缺席。要检测到没有值,您需要ValueEventListener

mRef.orderByChild("email").equalTo(val).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.getChildrenCount() == 0) {
            System.out.println("No user with email "+val);
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {
        throw firebaseError.toException(); // don't ignore onCancelled!
    }
});

答案 1 :(得分:0)

mQuery = databaseReference.limitToLast(1).orderByChild("email").equalTo(category);

        mQuery.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.i(TAG, "onDataChange: "+dataSnapshot.toString());
                GenericTypeIndicator<Map<String,UserModel>> t=new GenericTypeIndicator<Map<String,UserModel>>(){};

                try{
                      Map<String,UserModel> userList=dataSnapshot.getValue(t);
                }catch(Exception exception){
                    //Error UserInfo not present in firebase
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
               //Error wile accessing database
            }
        });