Search code examples
androidfirebasetwitterfirebase-realtime-database

Firebase database query like a twitter top tweets


Well I am using google github on firebase database. There are people comments if users like others comment, they can give a star (like). on the other hand I want to make a page which is showing only top comments which are upped. if I use this query:

Sample code is given below-:

package com.google.firebase.quickstart.database.fragment;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.Query;

    public class MyTopPostsFragment extends PostListFragment {

        public MyTopPostsFragment() {}

        @Override
        public Query getQuery(DatabaseReference databaseReference) {
            // [START my_top_posts_query]
            // My top posts by number of stars
            String myUserId = getUid();
            Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
                    .orderByChild("starCount");
            // [END my_top_posts_query]

            return myTopPostsQuery;
        }
    }

it will return all times top comments. how specify such as top comments week or day. also there a timestamp in my datasnapshoot


Solution

  • Firebase Realtime Database does not support chained queries. So a query like this:

    databaseReference.child("user-posts")
        .child(myUserId)
        .orderByChild("starCount")
        .orderByChild("timestamp");
    

    Is forbidden. Calling an order-by method multiple times in the same query throws an error. You can only use one order-by method at a time.

    To solve this, you can create an extra key to make it possible. A "post" can have a combined key for starCount and timestamp. Your new key should look like this:

    starCount_timestamp
    

    Then you can query your database based on this new key.