查询未能返回列表中正确的项目。 应该返回计数最多的15个项目。

huangapple go评论72阅读模式
英文:

Query not returning correct items in list. Should return items with largest count and list limit should be 15 items

问题

我需要使ArrayList只能有15个项目。我已经尝试了两种显而易见的方法:

if (mPostList.size() < 15)

if (mRecyclerView.getAdapter().getItemCount() < 15)

我尝试了这两种方法,但它们没有返回正确的项目。需要查询的项目是按从最多到最少的count进行查询的,但这两种方法都返回不应该在列表中的随机项目。

下面是整个方法的上下文。我该怎么做才能获得具有最大count的帖子,并且列表中只有15个项目?

如果我将其从Query更改为DatabaseReference,它可以工作,但时间太长了。

需要按count排序并将列表限制为15个项目。

那么如何在Query中限制列表为15个项目呢?

private void readPosts() {
    Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("count");
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            mPostList.clear();
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                Post post = dataSnapshot.getValue(Post.class);
                mPostList.add(post);
            }

            if (mPostList.size() == 0) {
                mProgressBar.setVisibility(View.GONE);
                mNoEventsFoundTextView.setVisibility(View.VISIBLE);
            } else {
                mProgressBar.setVisibility(View.GONE);
                mNoEventsFoundTextView.setVisibility(View.GONE);
            }

            Collections.sort(mPostList, (Post o1, Post o2) -> Long.compare(o2.getCount(), o1.getCount()));
            mPostAdapter.notifyDataSetChanged();
            mSwipeRefreshLayout.setRefreshing(false);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    });
}
英文:

I need to make it so that the ArrayList can only have 15 items. I have tried the two obvious things that one could do which is:

if (mPostList.size() &lt; 15)

and

if (mRecyclerView.getAdapter().getItemCount() &lt; 15)

I have tried both of those approaches, but they don't return the correct items. The items that are to be queried are by count from the most to the least, and both of those return random items that shouldn't be in the list.

Below you have the whole method for context. What can I do so that I get back the posts with the biggest count and only have 15 items in the list?

If I change it to DatabaseReference instead of Query it works but takes WAY TOO LONG.

Need it to be ordered by count and set the list limit to 15 items.

So how can I limit the list to 15 items for Query?

Posts
    -MFv4Q2HuSMeO20jFdvn
        city: &quot;New Orleans&quot;
        count: 13
        description: &quot;Who&#39;s down for a little nature hike with some g...&quot;
        postid: &quot;-MFv4Q2HuSMeO20jFdvn&quot;
        postimage: &quot;https://firebasestorage.googleapis.com/v0/b/eve...&quot;
        publisher: &quot;p3IeqP273ogiWuexi6w0bNGm9Mo2&quot;
        location: &quot;2615 Stonebriar Ridge Ct&quot;
        timestamp: 1598719111494

        private void readPosts() {
            Query query = FirebaseDatabase.getInstance().getReference(&quot;Posts&quot;).orderByChild(&quot;count&quot;);
            query.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    mPostList.clear();
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                        Post post = dataSnapshot.getValue(Post.class);
                            mPostList.add(post);
                    }
    
                    if (mPostList.size() == 0) {
                        mProgressBar.setVisibility(View.GONE);
                        mNoEventsFoundTextView.setVisibility(View.VISIBLE);
                    } else {
                        mProgressBar.setVisibility(View.GONE);
                        mNoEventsFoundTextView.setVisibility(View.GONE);
                    }
    
                    Collections.sort(mPostList, (Post o1, Post o2) -&gt; Long.compare(o2.getCount(), o1.getCount()));
                    mPostAdapter.notifyDataSetChanged();
                    mSwipeRefreshLayout.setRefreshing(false);
                }
    
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
        }


</details>


# 答案1
**得分**: 1

Firebase实时数据库查询始终按升序返回匹配的节点。因此,如果您想获取具有最高值的15个项目,有两种选择:

1. 从列表中获取**最后**的15个项目,然后在客户端对它们进行反转。此查询如下所示:

       query = FirebaseDatabase.getInstance().getReference("Posts")
                               .orderByChild("count").limitToLast(15)            

2. 在每个子节点中也存储一个反转的`count`值,并根据该值进行排序。因此,每个JSON将如下所示:

       Posts
           -MFv4Q2HuSMeO20jFdvn
               city: "New Orleans"
               count: 13
               invertedCount: -13
               ...

   查询将如下所示:

       query = FirebaseDatabase.getInstance().getReference("Posts")
                               .orderByChild("invertedCount").limitToFirst(15)


另请参见:

* https://stackoverflow.com/questions/34156996/firebase-data-desc-sorting-in-android

<details>
<summary>英文:</summary>

Firebase Realtime Database queries always return the matching nodes in ascending order. So if you want the 15 items with the highest values, you have two options:

1. Get the **last** 15 items from the list, and then reverse those client-side. The query for this would look like this:

       query = FirebaseDatabase.getInstance().getReference(&quot;Posts&quot;)
                               .orderByChild(&quot;count&quot;).limitToLast(15)            

2. Store an inverted `count` value in each child node too, and order on that. So each JSON would then look like this:

       Posts
           -MFv4Q2HuSMeO20jFdvn
               city: &quot;New Orleans&quot;
               count: 13
               invertedCount: -13
               ...

   And the query would be:

       query = FirebaseDatabase.getInstance().getReference(&quot;Posts&quot;)
                               .orderByChild(&quot;invertedCount&quot;).limitToFirst(15)


Also see:

* https://stackoverflow.com/questions/34156996/firebase-data-desc-sorting-in-android

</details>



huangapple
  • 本文由 发表于 2020年9月24日 23:48:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64049966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定