Robert Lu
Robert Lu

Reputation: 473

Java Firebase Search By Child Value

I'm trying to make an application which stores entries on Firebase. Each entry will have an author field to specify who wrote it. However, every post (regardless of author) will be pushed to a common parent. Is there a way to iterate through each entry under this parent and find all posts by a given author?

Upvotes: 0

Views: 4652

Answers (1)

Sunshinator
Sunshinator

Reputation: 950

You can use a Firebase Query. Basically, instead of downloading all the database and filtering yourself, you query your FirebaseReference on certain children's value. You can try something like this to retrieve all posts from the same author.

// Get your reference to the node with all the entries
DatabaseRefenrec ref = FirebaseDatabase.getInstance().getReference();

// Query for all entries with a certain child with value equal to something
Query allPostFromAuthor = ref.orderByChild("name_of_the_child_node").equalTo("author_name");

// Add listener for Firebase response on said query
allPostFromAuthor.addValueEventListener( new ValueEventListener(){
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot post : dataSnapshot.getChildren() ){
            // Iterate through all posts with the same author
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});

For better performances, consider indexing you database using Firebase rules. This makes Firebase saving your data in an ordered way so that queries are managed faster.

Upvotes: 1

Related Questions