0

I am using firebase realtime database in my application. I am pulling data with custom adapter in the message box. I want it to fetch old messages when I press the button. But orderbychild and orderbykey are not used together. What can I use instead of orderbykey() ?

RecyclerView recyclerViewlist;
    ProgressBar messageref ;

LinearLayoutManager linearLayoutManager ;

private final List<ModelMessageFragment> postListnew =new ArrayList<>();
    private AdapterMessageFragment adapterMessageFragment ;
private int itemPos = 0;
    private String mLastKey = "";
    private String mPrevKey = "";
    static final int total_ITEMS = 15 ;
    int currentpage = 1 ;


 mAuth = FirebaseAuth.getInstance();
        FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
        if(mFirebaseUser != null) {
            currentUserID = mFirebaseUser.getUid(); 

            Lastrefnew = FirebaseDatabase.getInstance().getReference().child("LastMessage").child(currentUserID);


adapterMessageFragment = new AdapterMessageFragment(postListnew);
            recyclerViewlist.setHasFixedSize(true);
            linearLayoutManager = new LinearLayoutManager(getContext());
            linearLayoutManager.setReverseLayout(true);
            linearLayoutManager.setStackFromEnd(true);
            recyclerViewlist.setLayoutManager(linearLayoutManager);
            recyclerViewlist.setAdapter(adapterMessageFragment);


            getallmessage();

 btnmoremessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currentpage++;
                    itemPos = 0;
                    getallmessagemore();

                    postListnew.clear();

                }
            });

public void getallmessage (){

        Query query = Lastrefnew.orderByChild("timestamp").limitToLast(currentpage * total_ITEMS);

        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            messageref.setVisibility(View.GONE);


                try {

                    ModelMessageFragment post = dataSnapshot.getValue(ModelMessageFragment.class);

                    itemPos++;

                    if(itemPos == 1){

                        String messageKey = dataSnapshot.getKey();

                        mLastKey = messageKey;
                        mPrevKey = messageKey;

                    }

                    postListnew.add(post);
                    adapterMessageFragment.notifyDataSetChanged();
                    recyclerViewlist.smoothScrollToPosition(recyclerViewlist.getAdapter().getItemCount());

                    recyclerViewlist.scrollToPosition(postListnew.size() - 1);
                    messageref.setVisibility(View.GONE);       
                    recyclerViewlist.setVisibility(View.VISIBLE);

                }catch (Exception e){

                }


            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
   if (messageref != null) {
                    messageref.setVisibility(View.GONE);
                }
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });




public void getallmessagemore (){


            Query messageQuery = Lastrefnew.orderByChild("timestamp").endAt(mLastKey).limitToLast(10);

        messageQuery.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                    messageref.setVisibility(View.GONE);

                    try {

                        ModelMessageFragment post = dataSnapshot.getValue(ModelMessageFragment.class);



  String messageKey = dataSnapshot.getKey();


                        if(!mPrevKey.equals(messageKey)){

                            postListnew.add(itemPos++, post);

                        } else {

                            mPrevKey = mLastKey;

                        }


                        if(itemPos == 1) {

                            mLastKey = messageKey;

                        }





                        adapterMessageFragment.notifyDataSetChanged();

                                   linearLayoutManager.scrollToPositionWithOffset(10, 0);

                          }catch (Exception e){

                         }


                }

                @Override
                public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                    if (messageref != null) {
                        messageref.setVisibility(View.GONE);
                        btnmoremessage.setVisibility(GONE);

                    }
                }

                @Override
                public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });




   

    }

AdapterMessageFragment:

public class AdapterMessageFragment extends RecyclerView.Adapter<AdapterMessageFragment.MessageFragmentViewHolder> {

    private List<ModelMessageFragment> postListnew;
    private FirebaseAuth mAuth;
    String currentUserid ;

    int[] photos={ R.drawable.c, R.drawable.e, R.drawable.xz,
            R.drawable.xzz, R.drawable.xzzz,R.drawable.kk,
    };

  
    public AdapterMessageFragment(List<ModelMessageFragment> postListnew) {
        this.postListnew = postListnew ;
        

    }

 public class MessageFragmentViewHolder extends RecyclerView.ViewHolder{
        CircleImageView profileImage ;
        ImageView onlinestatus , seenstatus;
        TextView  userName , userTime , messageinfooo;
        View mView;
        public MessageFragmentViewHolder(@NonNull View itemView) {
            super(itemView);

            profileImage =itemView.findViewById(R.id.messageprofileimageee);
            userName =itemView.findViewById(R.id.messagenameee);
            onlinestatus =itemView.findViewById(R.id.onlinestatus);
            seenstatus =itemView.findViewById(R.id.seenstatus);
            userTime =itemView.findViewById(R.id.messagetime);
            messageinfooo =itemView.findViewById(R.id.messageinfooo);

        }
    }

 @Override
    public MessageFragmentViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
           
                View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
                        R.layout.message_list_model, viewGroup, false);

                return new MessageFragmentViewHolder(menuItemLayoutView);

    }

@Override
    public void onBindViewHolder(@NonNull MessageFragmentViewHolder holder, int i) {

                mAuth = FirebaseAuth.getInstance();
                currentUserid = mAuth.getCurrentUser().getUid();

                ModelMessageFragment post = (ModelMessageFragment) postListnew.get(i);

                Random ran=new Random();
                int ii=ran.nextInt(photos.length);
        holder.profileImage.setImageResource(photos[ii]);

                DatabaseReference UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");

                String usersIDs = post.getcurrentUserid();

                UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if (snapshot.hasChild("name")){
                            final String myUsername = snapshot.child("name").getValue().toString();
                            holder.userName.setText(myUsername);
                        }

                        if (snapshot.hasChild("photoid")){
                            final String userphoto = snapshot.child("photoid").getValue().toString();
                            if (userphoto.equals("alien")){
                                holder.profileImage.setImageResource(R.drawable.alien50);
                            }else if (userphoto.equals("dragon")){
                                holder.profileImage.setImageResource(R.drawable.dragon50);
                            }else if (userphoto.equals("pug")){
                                holder.profileImage.setImageResource(R.drawable.pug50);
                            }else if (userphoto.equals("doge")){
                                holder.profileImage.setImageResource(R.drawable.doge50);
                         
                        }else {

                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });

                String getlastseen = post.getS();



                try {
                    if (getlastseen.equals("notseen")){
                        Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
                        holder.messageinfooo.setTypeface(boldTypeface);
                        holder.userTime.setTypeface(boldTypeface);
                        holder.userName.setTypeface(boldTypeface);
                        holder.userTime.getResources().getColor(R.color.messagefragmentnotseen);
                        holder.userName.getResources().getColor(R.color.messagefragmentnotseen);
                        holder.messageinfooo.getResources().getColor(R.color.messagefragmentnotseen);

                        holder.seenstatus.setVisibility(View.VISIBLE);
                    }else {

                    }
                }catch (Exception e){

                }

        holder.messageinfooo.setText(post.getL());
                String groupdate = post.gettimestamp();

                Long Timestamp2 = Long.parseLong(groupdate);
                Date timeD = new Date(Timestamp2 * 1000);
                SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss aa");
                String Time = sdf.format(timeD);



                String  gettime = zaman2(Time);
         
        holder.userTime.setText(gettime);


        holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent chatintent = new Intent(v.getContext(), Chat.class);
                        chatintent.putExtra("visit_user_id",post.getC());
                        v.getContext().startActivity(chatintent);


                    }
                });


@Override
    public int getItemCount() {
        return postListnew.size();
    }

    private String zaman2(String Time) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss aa");
        try {
            long time = sdf.parse(Time).getTime();
            long now = System.currentTimeMillis();
            CharSequence ago =
                    DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
            return ago+"";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

ModelMessageFragment:


public class ModelMessageFragment {
    public String l;
    public String d;
    public String timestamp;
    public String s;
    public String currentUserid ;



    public ModelMessageFragment(String l, String d, String timestamp, String s, String currentUserid ) {
        this.l = l;
        this.d = d;
        this.timestamp = timestamp;
        this.s = s;
        this.currentUserid = currentUserid ;


    }

    public String getL() {
        return l;
    }

    public void setL(String l) {
        this.l = l;
    }

    public String getD() {
        return d;
    }

    public void setD(String d) {
        this.d = d;
    }

    public String gettimestamp() {
        return timestamp;
    }

    public void settimestamp(String timestamp) {
        this.timestamp= timestamp;
    }

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    public String getcurrentUserid () {
        return currentUserid ;
    }

    public void setcurrentUserid (String currentUserid ) {
        this.currentUserid  = currentUserid ;
    }

    public ModelMessageFragment() {


    }
}

my db :

enter image description here

  • "But orderbychild and orderbykey are not used together" I'm not sure I understand what you mean there, and you've shared quite a lot of code. When you set breakpoints on every relevant line, run the code in a debugger, and then check the value of each variable on each line, which is the first line that doesn't do what you expect it to do? – Frank van Puffelen Oct 05 '22 at 23:26
  • @FrankvanPuffelen " Query messageQuery = Lastrefnew.orderByChild("timestamp").endAt(mLastKey).limitToLast(10); " this part not working. if i add ordeybykey to it: "Query messageQuery = Lastrefnew.orderByChild("timestamp").orderbykey().endAt(mLastKey).limitToLast(10)" I am getting multiple orderBy error. – Muratcan Yıldız Oct 06 '22 at 14:00
  • That is correct, each query can only contain a single `orderBy...` clause. If you want the results to be order on their key values, you'll have to re-order them in your application code. – Frank van Puffelen Oct 06 '22 at 15:35

1 Answers1

0

Each query on the Firebase Realtime Database can only contain a single orderBy... clause. If you want the results to be order on their key values, you'll have to re-order them in your application code.

This is typically easiest to do if you use addValueEventListener, loop over dataSnapshot.getChildren() in the onDataChange method, and then resort the list once you've processed all children. Also see the Firebase documentation on listening for a list of nodes with a value event listener and my answer to Query based on multiple where clauses in Firebase.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thank you frank. I didn't understand how to modify my own code accordingly. I would be very happy if you could write the code. – Muratcan Yıldız Oct 06 '22 at 19:53
  • Sorry, but that's not how Stack Overflow works. I included links where you can find more, including one to the documentation that shows how to loop over the results. If you get stuck implementing this yourself, edit your question to show what you tried. – Frank van Puffelen Oct 06 '22 at 20:28