在Firebase中按照Ascendening顺序排序

时间:2017-03-20 03:32:15

标签: android firebase firebase-realtime-database

我想在Firebase数据库上从上到下排序。谁能帮我?我试图使用集合,但它没有用。

启动回收站视图的活动

public class activity_ranking extends AppCompatActivity {
RecyclerView rv;

List<User> users;

Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ranking);


    rv = (RecyclerView)findViewById(R.id.recycler);

    rv.setLayoutManager(new LinearLayoutManager(this));

    users = new ArrayList<>();


    FirebaseDatabase database = FirebaseDatabase.getInstance();

    adapter = new Adapter(users);

    Collections.sort(users, new Comparator<User>(){
        public int compare(User obj1, User obj2)
        {
            // TODO Auto-generated method stub
            return (obj1.getStars() > obj2.getStars()) ? +1: (obj1.getStars() > obj2.getStars()) ? 1:0 ;
        }
    });

    rv.setAdapter(adapter);
    Query query = database.getReference().child("users").orderByChild("stars");

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            users.removeAll(users);
            for (DataSnapshot snapshot:
                    dataSnapshot.getChildren()) {
                User user = snapshot.getValue(User.class);


                users.add(user);

            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
}

MyClass用户

public class User {
public User() {
}

String username;
String name;
int stars;
String id;

public User(String username, String name, int stars, String id) {
    this.username = username;
    this.name = name;
    this.stars = stars;
    this.id = id;
}

public String getUsername() {
    return username;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getStars() {
    return stars;
}

public void setStars(int stars) {
    this.stars = stars;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}
}

1 个答案:

答案 0 :(得分:1)

要反转列表,请将项目添加到开头而不是结尾。所以而不是:

users.add(user);

DO

users.add(0, user);

请参阅:Java Arrays how to add elements at the beginning