我将数据存储在Firebase存储中.
Comment
具有属性的对象timestamp
.当我将数据从设备推送到Firebase时,我timestamp
使用currentTime 填充并存储在long
数据类型中.
当我检索数据时,firebaseRef.orderByChild("timestamp").limitToLast(15)
结果不是按照我的预期排序.
我甚至玩过规则而没有结果:
{ "rules": { ".read": true, ".write": true, ".indexOn": "streetrate", "streetrate": { ".indexOn": ".value" } } }
我试图储存timestamp
在String
数据类型,同样的问题.
Firebase可以按给定属性按升序对项目进行排序,然后返回前N个项目(limitToFirst()
)或最后N个项目(limitToLast()
).没有办法表明您希望项目按降序排列.
有两种方法可以获得您想要的行为:
使用Firebase查询获取正确的数据,然后在客户端重新排序
添加具有降序值的字段到数据
对于后一种方法,通常具有反转时间戳.
-1 * new Date().getTime();
如果您使用Recycler视图呈现该数据,我会发现一个很好的解决方案......
mLayoutManager = new LinearLayoutManager(getActivity()); mLayoutManager.setReverseLayout(true); mLayoutManager.setStackFromEnd(true); // And set it to RecyclerView mRecyclerView.setLayoutManager(mLayoutManager);
它将反转数据呈现...
private static class ChatMessageViewHolder extends RecyclerView.ViewHolder { TextView messageText; TextView nameText; public ChatMessageViewHolder(View itemView) { super(itemView); nameText = (TextView)itemView.findViewById(android.R.id.text1); messageText = (TextView) itemView.findViewById(android.R.id.text2); } } FirebaseRecyclerViewAdapteradapter; ref = new Firebase("https:// .firebaseio.com"); RecyclerView recycler = (RecyclerView) findViewById(R.id.messages_recycler); recycler.setHasFixedSize(true); ////////////////////////////////////////////////////////// mLayoutManager = new LinearLayoutManager(getActivity()); mLayoutManager.setReverseLayout(true); mLayoutManager.setStackFromEnd(true); recycler.setLayoutManager(mLayoutManager); ///////////////////////////////////////////////////////// adapter = new FirebaseRecyclerViewAdapter (ChatMessage.class, android.R.layout.two_line_list_item, ChatMessageViewHolder.class, mRef) { public void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatMessage chatMessage) { chatMessageViewHolder.nameText.setText(chatMessage.getName()); chatMessageViewHolder.messageText.setText(chatMessage.getMessage()); } }; recycler.setAdapter(mAdapter);
我没有看到任何反转数据的选项.但One Brute的方法是获取数据.
ListmList=new ArrayList(); public void onDataChange(DataSnapshot dataSnapshot) { mList.clear(); for(DataSnapshot children: dataSnapshot.getChildren()){ ModelClass modelClass=children.getValue(ModelClass.class); mList.add(modelClass); } Collections.reverse(mList); Adapter.notifyDataSetChanged(); }
我通过扩展FirebaseListAdapter并覆盖getItem方法解决了问题:
public abstract class ReverseFirebaseListAdapterextends FirebaseListAdapter { public ReverseFirebaseListAdapter(Activity activity, Class modelClass, int modelLayout, Query ref) { super(activity, modelClass, modelLayout, ref); } public ReverseFirebaseListAdapter(Activity activity, Class modelClass, int modelLayout, DatabaseReference ref) { super(activity, modelClass, modelLayout, ref); } @Override public T getItem(int position) { return super.getItem(getCount() - (position + 1)); }
}