Cannot retrieve data in ascending order

一世执手 提交于 2021-02-05 10:46:07

问题


I want to retrieve data in ascending order, but received data somehow added to recyclerview in descending order.

Firebase Database: database structure

What I am doing:

    DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("/Teacher");

    Query query = mDatabase.orderByChild("rating");

    FirebaseRecyclerOptions<Teacher> options =
            new FirebaseRecyclerOptions.Builder<Teacher>()
                    .setQuery(query, Teacher.class)
                    .build();

    FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Teacher, TeacherViewHolder>(options) {
        @NonNull
        @Override
        public TeacherViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.teacher_list_item, parent, false);

            return new TeacherViewHolder(view);

        }

        @Override
        protected void onBindViewHolder(@NonNull final TeacherViewHolder holder, int position, @NonNull final Teacher model) {

           // some stuff here

        }
    };

回答1:


Since you can't do that natively with the RTDB, you'll probably want to do something like this:

LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);

See https://stackoverflow.com/a/27727398/4548500 for more details.




回答2:


To get a sorted and filtered result, you have to pass a query into the FirebaseRecyclerAdapter constructor:

public MyFireAdapterDiasFiestaRecyclerView(
    Class<DiaFiestaMeta> modelClass, 
    int modelLayout, 
    Class<MyFireViewHolder> viewHolderClass, 
    Query query) {
    ...

And then invoke it with a query that orders and filters:

adapter = new MyFireAdapterDiasFiestaRecyclerView(
   DiaFiestaMeta.class,
   layout_that_you_use,
   MyFireViewHolder.class,
   ref.orderByChild("property_to_sort_and_filter_on").equalTo("value_to_filter_on")
);


来源:https://stackoverflow.com/questions/49832057/cannot-retrieve-data-in-ascending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!