首页 > 解决方案 > Firestore whereEqualto()在Android应用程序中查询的不正确行为

问题描述

我的数据库由一个名为的集合组成,该集合具有songs以下字段:artistemail和。目前所有文档中的字段都是空字符串。这是其中一个条目的图片。linknameemail

这是我在我的 android 应用程序中运行的查询:

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);
        firebaseAuth = FirebaseAuth.getInstance();

        FirebaseFirestore db = FirebaseFirestore.getInstance();

        TextView userinfo = (TextView)findViewById(R.id.link);
        FirebaseUser userauth = firebaseAuth.getCurrentUser();

db.collection("songs").whereEqualTo("email",userauth.getEmail()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>(){
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Document found in the offline cache
            userinfo.setText("User found");
        } else {
           userinfo.setText("User not found");
        }
    }
});


    }

User found即使所有电子邮件条目都是空字符串,TextView 仍在打印。预期的行为是User not found

标签: javaandroidfirebasegoogle-cloud-platformgoogle-cloud-firestore

解决方案


如果你只检查一个任务是否成功,并不意味着你得到了结果。这意味着您的查询已完成,没有错误。如果您需要知道查询是否返回所需的结果,那么您应该在代码中检查:

if (task.isSuccessful()) {
    QuerySnapshot snapshot = task.getResult();
    if (snapshot.isEmpty()) {
        userinfo.setText("User not found");
    } else {
        userinfo.setText("User found");
    }
} else {
    Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}

“找不到用户”消息将设置为您的userinfoTextView。


推荐阅读