如果时间戳字段,Firebase使用endAt

时间:2017-01-10 19:21:22

标签: android firebase firebase-realtime-database

我有这个字段的记录:

age: 25
timestamp: 1484089199472

此记录由:

插入
@Exclude
public Map<String, Object> toMap() {
    HashMap<String, Object> result = new HashMap<>();

    result.put("age", age);
    result.put("timestamp", ServerValue.TIMESTAMP);
    return result;
}

如果我使用endAt(24,"age")而不是其工作,则该项目是不可见的。

但是,如果我想在时间戳中使用endAt它不起作用。例如: endAt(100000,"timestamp")并且该行保持可见。 为什么?

这是检查类型?

我该如何过滤它?

我什么都不知道! :( 我希望有一个人可以帮助我! 谢谢!

修改

查询获取实际日行

 @Override
    public Query getQuery(final DatabaseReference databaseReference) {
        Date endTime = new Date();
        endTime.setHours(23);
        endTime.setMinutes(59);
        endTime.setSeconds(59);

        return databaseReference
                .child("toplist")
                .endAt(endTime.getTime(),"timestamp")
                .orderByChild("point")
                .limitToFirst(50);

    }

数据

@IgnoreExtraProperties
public class Rank{

    public int number;
    public String username;
    public int point;


    // [START post_to_map]
    @Exclude
    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("number", number);
        result.put("username", username);
        result.put("point", point);
        result.put("timestamp", ServerValue.TIMESTAMP);
        return result;
    }

}

添加新的随机项

private void writeNewRandomTopListItem() {
        Random rnd = new Random();
        Rank item = new Rank();
        item.username = "Test " + rnd.nextInt(20000);
        item.point = rnd.nextInt(2000000);

        mDatabase.child("toplist").push().setValue(item.toMap());
    }

适配器

Query postsQuery = getQuery(mDatabase);
        mAdapter = new FirebaseRecyclerAdapter<Rank, PostViewHolder>(Rank.class, R.layout.item_post, PostViewHolder.class, postsQuery) {
            @Override
            protected void populateViewHolder(final PostViewHolder viewHolder, final Rank model, final int position) {

                viewHolder.bindToPost(model,position);
            }
        };
        mRecycler.setAdapter(mAdapter);

...

 toplist
   -Ka8m3hN-vRjPZhKH3Rt
     number: 0
     point:  1269424
     timestamp: 148407253222471
     username:  "Test 19727"
   -Ka8m3hWRIQKL7faNqUS
     number:  0
     point:  1398061
     timestamp:  1484075322472
     username: "Test 17679"

2 个答案:

答案 0 :(得分:4)

您应首先由points孩子订购您的节点,然后在客户端按@Override public Query getQuery(final DatabaseReference databaseReference) { Date endTime = new Date(); endTime.setHours(23); endTime.setMinutes(59); endTime.setSeconds(59); return databaseReference.child("toplist").orderByChild("timestamp") .endAt(endTime.getTime()).limitToFirst(50); } 订购收到的商品。这被描述为here

我建议您改用此查询:

timestamp

通过这种方式,您可以告诉Firebase按其子节点之一对节点进行排序,在这种情况下,这些子节点将为RecyclerView。希望这会有所帮助。

接下来,您需要在客户端对数据进行排序。这样做的一个问题是,来自firebase的实时更改不会重新排序svg+xml内的项目。

我再次建议您通过this回答。

答案 1 :(得分:0)

  

经过几天的实验,我解决了这个问题。

重点是

  

我很惊讶地发现即使查询可以通过深度嵌套来排序   儿童,但仅对 ONE 级儿童有效!

在这种情况下,我尝试先将节点再下一层,并对其查询特定时间,然后它就可以工作了。

这是我在Firebase实时数据库上的数据树: enter image description here

为读取存储在Firebase中的POJO模型,我设置了一个为我服务的助手类。 因此,我在运行FirebaseDatabaseHelper.getInstance().readCatalogFromDatabase(Card.class, listener, start, end);的同时用最新的数据库更新了UI。

关于我的FirebaseDatabaseHelper,有两种相对的方法可以很好地帮助我读取数据库reference()上的模型,这是指父节点拥有很多模型,例如“ / Card / user_id”节点,其中有许多子代,这意味着卡片的详细信息在/ Card / user_id / card_id”。

/**
 * attaches listener to obtain values at child locations of "catalog/" storing lots of models in JSON tree
 * reads values created in a specific period and ordered by date
 *
 * catalog: "Card" for card
 *          "Comment" for comment
 *
 * It's surprised to found out even query can be ordered by deep nested children, but children ONE more level down only
 * Being such circumstance, go for node one more level down first and do query for a specific period on it
 */
public void readCatalogFromDatabase(final Class<?> clazz, final OnReadDatabaseChildEventListener child_listener, final long start, final long end) {
    //Logger.d(">>> end at date before:" + (end/(1*24*60*60*1000) - start/(1*24*60*60*1000)));
    Logger.d(">>> start:" + start + ", end:" + end);
    DatabaseReference referenceCatalog;
    OnReadDatabaseValueEventListener ids_listener;
    String catalog;
    if (clazz.getName().equals(Card.class.getName())) {
        ids_listener = new OnReadDatabaseValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List<String> ids = new LinkedList<>();
                Logger.d("... user count:" + dataSnapshot.getChildrenCount());
                /**
                 * $ROOT/catalog/user_id/CardId/CardId
                 * $ROOT/catalog/user_id/CardId/ProfilePhoto
                 * $ROOT/catalog/user_id/CardId/ProfileTitle
                 * $ROOT/catalog/user_id/CardId/ProfileName
                 * $ROOT/catalog/user_id/CardId/ProfileID
                 * $ROOT/catalog/user_id/CardId/ArticleTitle
                 * $ROOT/catalog/user_id/CardId/ArticleContent
                 * $ROOT/catalog/user_id/CardId/ArticleCount
                 * $ROOT/catalog/user_id/CardId/ArticlePhoto
                 * $ROOT/catalog/user_id/CardId/ArticlePhotoFileName
                 * $ROOT/catalog/user_id/CardId/Distance
                 * $ROOT/catalog/user_id/CardId/Date
                 *      ^[key]  :[value]                -> initial
                 *              ^[key]  :[value]        -> 1th for-loop
                 */
                for (DataSnapshot snapShotOfUserId : dataSnapshot.getChildren()) {
                    Logger.d("... user(" + snapShotOfUserId.getKey() + ") post count:" + snapShotOfUserId.getChildrenCount());
                    ids.add(snapShotOfUserId.getKey());
                }
                for (String id : ids) readListFromDatabase(clazz, id, child_listener, start, end);
                FirebaseDatabaseHelper.getInstance().detachValueEventListener(this);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                child_listener.onCancelled(databaseError);
                FirebaseDatabaseHelper.getInstance().detachValueEventListener(this);
            }
        };
        catalog = Card.class.getSimpleName();
        referenceCatalog = getDatabaseChild(catalog, null, null);
        referenceCatalog.orderByKey().limitToLast(COUNT_ON_PAGE).addListenerForSingleValueEvent(ids_listener);
        mValueEventListeners.put(ids_listener, referenceCatalog);
    } else if (clazz.getName().equals(Comment.class.getName())) {
        ids_listener = new OnReadDatabaseValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List<String> ids = new LinkedList<>();
                Logger.d("... card count:" + dataSnapshot.getChildrenCount());
                /**
                 * $ROOT/catalog/card_id/CommentId/CardId
                 * $ROOT/catalog/card_id/CommentId/CommentId
                 * $ROOT/catalog/card_id/CommentId/ProfilePhoto
                 * $ROOT/catalog/card_id/CommentId/ProfileName
                 * $ROOT/catalog/card_id/CommentId/ProfileID
                 * $ROOT/catalog/card_id/CommentId/Comment
                 * $ROOT/catalog/card_id/CommentId/Distance
                 * $ROOT/catalog/card_id/CommentId/Date
                 *      ^[key]  :[value]                    -> initial
                 *              ^[key]  :[value]            -> 1th for-loop
                 */
                for (DataSnapshot snapShotOfCardId : dataSnapshot.getChildren()) {
                    Logger.d("... card(" + snapShotOfCardId.getKey() + ") comment count:" + snapShotOfCardId.getChildrenCount());
                    ids.add(snapShotOfCardId.getKey());
                }
                for (String id : ids) readListFromDatabase(clazz, id, child_listener, start, end);
                FirebaseDatabaseHelper.getInstance().detachValueEventListener(this);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                child_listener.onCancelled(databaseError);
                FirebaseDatabaseHelper.getInstance().detachValueEventListener(this);
            }
        };
        catalog = Comment.class.getSimpleName();
        referenceCatalog = getDatabaseChild(catalog, null, null);
        referenceCatalog.orderByKey().limitToLast(COUNT_ON_PAGE).addListenerForSingleValueEvent(ids_listener);
        mValueEventListeners.put(ids_listener, referenceCatalog);
    }

然后转到

 /**
 * attaches listener to obtain values at child locations of "catalog/id/" storing list of models in JSON tree
 * reads values created in a specific period and ordered by date
 *
 * id: user id for card
 *     card id for comment
 *
 * query can be ordered by deep nested ONE more level down children
 */
public void readListFromDatabase(Class<?> clazz, String id, OnReadDatabaseChildEventListener listener, long start, long end) {
    //Logger.d(">>> end at date before:" + (end/(1*24*60*60*1000) - start/(1*24*60*60*1000)));
    Logger.d(">>> start:" + start + ", end:" + end + ", id:" + id);
    DatabaseReference referenceCatalog;
    Query query;
    String catalog;
    if (clazz.getName().equals(Card.class.getName())) {
        catalog = Card.class.getSimpleName();
        referenceCatalog = getDatabaseChild(catalog, id, null);
        query = referenceCatalog.orderByChild("Date").startAt(start).endAt(end).limitToLast(COUNT_ON_PAGE);
        query.addChildEventListener(listener);
        mChildEventListeners.put(listener, referenceCatalog);
    } else if (clazz.getName().equals(Comment.class.getName())) {
        catalog = Comment.class.getSimpleName();
        referenceCatalog = getDatabaseChild(catalog, id, null);
        query = referenceCatalog.orderByChild("Date").startAt(start).endAt(end).limitToLast(COUNT_ON_PAGE);
        query.addChildEventListener(listener);
        mChildEventListeners.put(listener, referenceCatalog);
    }
}

关于数据库参考,

/**
 * gets a database reference to location headed with "/catalog/", "/id/" and "/key/" as prefixes(to a child location in JSON tree)
 *
 * id: user id for card
 *     card id for comment
 * key:
 *     card id for card
 *     comment id for comment
 */
private DatabaseReference getDatabaseChild(String catalog, String id, String key) {
    Logger.d(">>>");
    DatabaseReference reference;
    if (catalog == null) {
        if (id == null) {
            if (key == null) {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference();
            } else {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference(key);
            }
        } else {
            if (key == null) {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference(id);
            } else {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference(id + "/" + key);
            }
        }
    } else {
        if (id == null) {
            if (key == null) {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference(catalog);
            } else {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference(catalog + "/" + key);
            }
        } else {
            if (key == null) {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference(catalog + "/" + id);
            } else {
                Logger.d("... catalog:" + catalog + ", id:" + id + ", key:" + key);
                reference = FirebaseDatabase.getInstance().getReference(catalog + "/" + id + "/" + key);
            }
        }
    }
    return reference;
}

这就是我在特定时期查询的方式。

  

此外,我发现了一些有关人们应该致电的答案   addChildEventListener()之后的orderByChild();但是,之后   我说进行实验

Query query;
query = referenceCatalog.orderByChild("Date").startAt(start).endAt(end).limitToLast(COUNT_ON_PAGE);
query.addChildEventListener(listener);

referenceCatalog.orderByChild("Date").startAt(start).endAt(end).limitToLast(COUNT_ON_PAGE).addChildEventListener(listener);
  

它们是相同的。

我认为它们的区别仅在于人们使用Java进行匿名编程的方式 是否上课。