简体   繁体   中英

How can I create a ranked leaderboard in Firebase?

There is a point system in my application. I want to create an ordered list of points in a part. It will be in order from highest score to lowest score. In the code I wrote, this system does not work correctly. not ranked from highest to lowest score. Newly rated users appear at the top. How can I fix this problem? I want it sorted from highest score to lowest score.

Scoreboard class:

DatabaseReference UsersRef, RatingsRef;
int currentpage = 1 ;
static final int total_ITEMS = 10 ;
RecyclerView scorrecy ;

UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
RatingsRef = FirebaseDatabase.getInstance().getReference().child("Ratings");
RatingsRef.keepSynced(false);

getScor();

  public void getScor(){

        FirebaseRecyclerOptions<ScorModel> options =
                new FirebaseRecyclerOptions.Builder<ScorModel>()
                        .setQuery(RatingsRef.orderByChild("puan").limitToLast(currentpage * total_ITEMS),ScorModel.class)
                        .build();

        FirebaseRecyclerAdapter<ScorModel,ScorViewHolder> adapter
                =new FirebaseRecyclerAdapter<ScorModel, ScorViewHolder>(options)
        {

            @Override
            protected void onBindViewHolder(@NonNull final ScorBoard.ScorViewHolder holder, int position, @NonNull ScorModel model) {
                final String visit_user_id = getRef(position).getKey();  

                UsersRef.child(visit_user_id).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            if (dataSnapshot.hasChild("isim")){
                                final String myUsername = dataSnapshot.child("isim").getValue().toString();
                                holder.userName.setText(myUsername);
                            }

                    }

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

                    }
                });
                RatingsRef.child(visit_user_id).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.hasChild("puan")){
                            final String myPoint = dataSnapshot.child("puan").getValue().toString();
                            holder.userPoint.setText(myPoint+" "+"Puan");
                        }else  {
                            holder.userPoint.setText("0 Puan");
                        }

                    }

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

                    }
                });

            }

            @NonNull
            @Override
            public ScorBoard.ScorViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.scorboard_model_layout,viewGroup,false);
                ScorBoard.ScorViewHolder viewHolder = new ScorBoard.ScorViewHolder(view);
                return  viewHolder;
            }
        };

        adapter.startListening();
        scorrecy.setAdapter(adapter);

    }

    public static class ScorViewHolder extends RecyclerView.ViewHolder{
        TextView  userName , userPoint;
        View mView;

        public ScorViewHolder(@NonNull View itemView) {
            super(itemView);
            mView= itemView;

            userName =itemView.findViewById(R.id.rank_username);
            userPoint =itemView.findViewById(R.id.point);
        }
    }

ScorModel;

  public String scor, username , currentUserID ;

    public ScorModel(){

    }

    public ScorModel(String scor,String username , String currentUserID) {
        this.scor= scor;
        this.username = username;
        this.currentUserID = currentUserID;

    }

  public String getScor() {
        return scor;
    }

    public void setScor(String scor) {
        this.scor = scor;
    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

Myy DB Ratings;

enter image description here

Update:

RatingsRef = FirebaseDatabase.getInstance().getReference().child("Ratings");
      
 RatingsRef.child(currentUserID).child("Ratings").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                double sum =  0.0;

                try {
                    for (DataSnapshot ds: dataSnapshot.getChildren()) {
                        Map<String,Object> map = (Map<String, Object>) ds.getValue();
                        Object rating =  map.get("rating");
                        Double pvalue = Double.parseDouble(String.valueOf(rating));
                        sum += pvalue;



                        Map userpoint = new HashMap();
                        userpoint .put("puan", String.valueOf(sum));

                        RatingsRef.child(currentUserID).updateChildren(userpoint );


                    }
                }catch (Exception e){

                }


            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException(); // don't ignore errors
            }
        });

You cannot get the desired results, because your puan field holds a value of type string and not a number. One thing to remember is that when you order strings the results are ordered lexicographically . For example, 10 is placed before 2. See an example below:

1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3

So the best option that you have is to change the type of the field to be number and not string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM