You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Cloud Firestore:如何查询用户名是否存在并返回布尔值

Fixing Firestore User Existence Check for Your Android App

Hey there! Let's work through this Firestore user check issue together. The core problem here is that Firestore queries are asynchronous—you can't just check if the Query object itself is "true" or "false" because it doesn't hold the result yet. Instead, we need to run the query, listen for its completion, then convert the result into a boolean value we can use.

Step 1: Update the Button Click Logic to Handle Async Query

First, let's adjust your button click listener to actually execute the query and wait for the result from Firestore:

continueBtn = findViewById(R.id.continue_btn);
continueBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Make sure we have a valid username input first
        String userName = mUserName.getText().toString().trim(); // Assume mUserName is your EditText
        if (userName.isEmpty()) {
            Toast.makeText(MainActivity.this, "Please enter a name!", Toast.LENGTH_SHORT).show();
            return;
        }

        // Create the query
        CollectionReference usersRef = database.collection("users");
        Query findNameQ = usersRef.whereEqualTo("name", userName);

        // Execute the query and listen for the result
        findNameQ.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    // Check if any documents matched the query
                    boolean userExists = !task.getResult().isEmpty();
                    // Pass the boolean result to your authenticate method
                    authenticateUser(userExists, userName);
                } else {
                    // Handle query failures (e.g., network issues, permissions)
                    Toast.makeText(MainActivity.this, "Error checking user: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
});

Step 2: Modify authenticateUser to Use the Boolean Value

Now, update your authenticateUser method to accept the boolean userExists parameter instead of the Query object. This lets you directly check if the user exists:

private void authenticateUser(boolean userExists, String userName) {
    if (userExists) {
        Toast.makeText(this, "User exists!", Toast.LENGTH_SHORT).show();
        // Add logic here to proceed to the next activity for existing users
    } else {
        Toast.makeText(this, "User doesn't exist! Creating new user...", Toast.LENGTH_SHORT).show();
        // Create a new user in Firestore
        database.collection("users")
                .add(new User(userName)) // Replace with your actual data model class
                .addOnSuccessListener(documentReference -> {
                    Toast.makeText(MainActivity.this, "New user created successfully!", Toast.LENGTH_SHORT).show();
                    // Proceed to next activity after creating the user
                })
                .addOnFailureListener(e -> {
                    Toast.makeText(MainActivity.this, "Failed to create user: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
    }
}

Key Notes to Remember:

  • Firestore is asynchronous: Queries don't return results immediately—you have to use listeners like addOnCompleteListener to get the data once it's available.
  • Check QuerySnapshot emptiness: task.getResult().isEmpty() tells us if there are no matching documents. Reversing this with ! gives us our userExists boolean.
  • Input validation: Always check that the username isn't empty before running the query to avoid unnecessary Firestore calls.
  • Error handling: Don't forget to handle cases where the query fails (like no internet or missing Firestore permissions).

内容的提问来源于stack exchange,提问作者Adrian Robertson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:54:36