如何在if else条件下使用firebase查询

时间:2016-07-17 12:58:43

标签: java android if-statement firebase firebase-realtime-database

这里是onclick按钮的代码,我想要做的是点击他的按钮应用程序必须从firebase数据库中获取电子邮件,如果成功它必须显示在编辑文本中,其他电子邮件显示在编辑 - 未找到电子邮件的文本,在这里我可以获取电子邮件并显示在编辑文本中找到的电子邮件但是无法显示未找到的电子邮件(否则是代码的一部分)而是我在控制台中获取此信息

  

W/PersistentConnection: pc_0 - Using an unspecified index. Consider adding '".indexOn": "email"' at /users/users to your security and Firebase rules for better performance

conbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            Firebase ref = new Firebase("https://(refrence of firebse database)");


            final String searchEmail = emailcon.getText().toString().trim();
            final Query query =   ref.orderByChild("email").equalTo(searchEmail);

            query.addValueEventListener(new ValueEventListener()
            {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot)
                {

                    for (DataSnapshot child : dataSnapshot.getChildren())
                    {
                        final String fetchEmail;
                        Map<?, ?> value = (Map<?, ?>) child.getValue();
                        Log.d("main2activity ","User data : "+ value);
                        fetchEmail = (String) value.get("email");
                        Log.d("main2activity ","User email : "+ fetchEmail);
                        if (searchEmail.equals(fetchEmail))
                        {
                            emailcon.setText("email found hurray "+query.getRef());
                        }
                        else
                        {
                            emailcon.setText("still no email found!!");
                        }
                    }
                }
                @Override
                public void onCancelled(FirebaseError firebaseError) {

                }
            });
        }
    });

1 个答案:

答案 0 :(得分:2)

由于您正在触发查询,因此您将获得一个可包含0个或更多子节点的快照。如果它包含任何子女,则这些孩子将拥有您在equalTo()

中使用的电子邮件地址

您需要稍微区别对待onDataChange()

query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.hasChildren()) {
            for (DataSnapshot child : dataSnapshot.getChildren()) {
                emailcon.setText("email "+searchEmail+" found at URL "+child.getRef());
            }
        }
        else {
            emailcon.setText("still no email found!!");
        }
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
    }
});