在MainActivity
内,我有这个功能:
public void sortingData() {
mRootRef = new Firebase("https://fyp-1-43a27.firebaseio.com/User");
dbSortAllData = FirebaseDatabase.getInstance().getReference();
ListView mLvScore = (ListView) findViewById(R.id.lvScore);
final List<UserInformation> listScore = new LinkedList<>();
final ArrayAdapter<UserInformation> adapter
= new ArrayAdapter<UserInformation>
(this, R.layout.scoreboard_row, listScore) {
@NonNull
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = getLayoutInflater().inflate(R.layout.scoreboard_row, parent, false);
}
UserInformation item = listScore.get(position);
((TextView) view.findViewById(R.id.tvScoreName)).setText(item.getName());
((TextView) view.findViewById(R.id.tvScorePoint)).setText(item.getScore());
return view;
}
};
mLvScore.setAdapter(adapter);
com.firebase.client.Query queryRef = mRootRef.orderByChild("score").startAt("score").endAt("score").limitToFirst(50);
queryRef.addChildEventListener(new com.firebase.client.ChildEventListener() {
@Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
UserInformation sI = dataSnapshot.getValue(UserInformation.class);
listScore.add(sI);
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
我的模特课程:
public class UserInformation implements Comparable<UserInformation> {
public String name;
public String age;
public String score;
public UserInformation() {}
public UserInformation(String name, String age, String score) {
this.name = name;
this.age = age;
this.score = score;
}
// ... Getters and Setters here.
}
这些代码可以工作,从最低到最高排序。
我的问题是如何从最高到最低排序?建议和建议非常感谢。
答案 0 :(得分:1)
您可以在客户端重新排序数据 - 只需反转列表。
编辑: 如果要反转列表,可以使用:
Collections.reverse(listScore);
adapter.notifyDataSetChanged();
您也可以将从数据库中获取的每个元素添加到列表的前面,以便以相反的顺序获取它:
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
UserInformation sI = dataSnapshot.getValue(UserInformation.class);
listScore.addFirst(sI);
adapter.notifyDataSetChanged();
}
并将listScore的声明更改为:
final LinkedList<UserInformation> listScore = new LinkedList<>();
答案 1 :(得分:0)
如果你想以相反的顺序,那么创建一个额外的密钥并存储newKey =值(乘以)-1,而不是简单的顺序。 我通过反转ArrayList尝试了其他解决方案但是当你将新数据添加到现有列表时它会变得更糟。
As you can see my priority score in negative so I can write
databaseReference = FirebaseDatabase.getInstance()。getReference() 。.child( “节点”)子( “事件”)orderByChild( “priorityScore”);