是否可以在列表视图中颠倒顺序?

时间:2019-05-28 17:32:53

标签: java android firebase-realtime-database

当我从firebase实时数据库中获取数据时,数据会自动以升序列出,但是我试图将放入数组列表中的值以相反的顺序列出,而不是以升序列出。

使用列表视图时是否可以对值进行逆序排序?
目前使用的代码是:

    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: 0
John Doe III - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79
John Doe IV - Steps: 88
John Doe II - Steps: 111

首选输出:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0

Collections.reverse(arrayList);添加到代码中时,输出为:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe III - Steps: 0
John Doe VI - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式将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 );

否则,每次调用onDataChange()时,arrayList对象将被颠倒,其顺序将被混淆。