当我从 firebase 实时数据库获取数据时,它会自动按升序列出,但我试图让我放入 arraylist 的值以相反的顺序而不是升序列出。使用 listview 时是否可以对值进行相反的排序?目前使用的代码是: Query query = userRef.orderByChild("totalNumberOfSteps"); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.getChildren()) { String username = ds.child("username").getValue(String.class); long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class); Log.d(TAG , username + " - Steps: " + totalNumberOfSteps); arrayList.add(new String(username + " - " + "steps: " + totalNumberOfSteps)); arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , arrayList); listView.setAdapter(arrayAdapter); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.d(TAG , databaseError.getMessage()); //Don't ignore errors! } }; query.addListenerForSingleValueEvent(valueEventListener);}}此代码的当前输出是:John Doe VI - Steps: 0John Doe III - Steps: 0John Doe V - Steps: 12John Doe I - Steps: 79John Doe IV - Steps: 88John Doe II - Steps: 111首选输出:John Doe II - Steps: 111John Doe IV - Steps: 88John Doe I - Steps: 79John Doe V - Steps: 12John Doe III - Steps: 0John Doe VI - Steps: 0添加Collections.reverse(arrayList);到代码时,输出为:John Doe II - Steps: 111John Doe IV - Steps: 88John Doe III - Steps: 0John Doe VI - Steps: 0John Doe V - Steps: 12John Doe I - Steps: 79
1 回答
肥皂起泡泡
TA贡献1829条经验 获得超6个赞
您可以在将 ArrayList 提供给 ArrayAdapter 之前反转它:
Collections.reverse(arrayList);
arrayList在你的情况下,在反转它并将它传递给 ArrayAdapter 的构造函数之前复制:
ArrayList<> tmpArr = new ArrayList<>(arrayList);
Collections.reverse(tmpArr);
arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , tmpArr );
否则,arrayList每次调用 onDataChange() 时对象都会被反转,并且它的顺序会被混淆。
添加回答
举报
0/150
提交
取消