Pedro Silveira
Pedro Silveira

Reputation: 69

How to make a query in Firebase similar to a SQL query?

I'm trying to develop an application for Android using Java. I am using the NoSQL Firebase database. However, it is very different from what I have learned so far, so I would like you to help me do something like this:

SELECT "name" FROM users WHERE email = "[email protected]"

using Firebase syntax. Could you help me?

Upvotes: 1

Views: 2864

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

In the world of NoSQL databases, a query that looks like this:

SELECT "name" FROM users WHERE email = "[email protected]"

Can be written in two ways. If you are using Firebase Realtime Database , the query should look like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query query = usersRef.orderByChild("email").equalTo("[email protected]");

And if you are using Cloud Firestore, the query should look like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
Query query = usersRef.whereEqualTo("email", "[email protected]");

Edit:

According to you comment, to get the name, please use the above lines along with the following lines of code:

ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            Log.d(TAG, name);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

Upvotes: 6

Related Questions