按降序排列Firebase数据[重复]

问题描述 投票:0回答:1

我想创建高分列表视图,并使用orderByValue将条目按降序显示,但是我将它们按升序进行排序,但是当对我的arraylist使用Collections.reverse()时,条目仍然不会颠倒ListView。

 private Query reference; //database reference
private ListView ListView; //creating listview
private ArrayList<String> arrayList = new ArrayList<>();

private ArrayAdapter<String> adapter; //creating array adapter
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_high_scores);


    reference = FirebaseDatabase.getInstance().getReference("Highscores").orderByValue(); //reference the highscore section in database



    ListView = (ListView) findViewById(R.id.list_view); //find the list view in the xml


    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList); // set the adapter to the list
    Collections.reverse(arrayList);

    ListView.setAdapter(adapter);

    reference.addChildEventListener(new ChildEventListener() { // add a child listener for the database
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            String value = dataSnapshot.getValue().toString(); // convert the values in the databse to string
            arrayList.add(value); //add them to the arraylist
            adapter.notifyDataSetChanged(); //notify that the dataset has changed



        }

数据库中的数据为

{“ -M4FPEiJ_DVc9kaQrebz”:0,

“-M4FPIuMbArT6KjtrDtO”:6,

“-M4FPP5EdC1CaKgOVECX”:17,

“-M4FPTWg7JkKRvWakRkH”:12,

“-M4FPYPNVZIjhBM6gVWW”:11,

“-M4FPbL9I-fsQwRvVIFX”:5}

答案:

无论如何,通过简单地在0索引处简单地添加到arraylist来解决此问题,所有其他元素都被简单地移到了右边,导致listview降序排列。

            String value = dataSnapshot.getValue().toString(); // convert the values in the databse to string
            arrayList.add(0, value); //add them to the arraylist
            adapter.notifyDataSetChanged(); //notify that the dataset has changed
java android sorting firebase-realtime-database leaderboard
1个回答
0
投票

reference.addChildEventListener(new ChildEventListener(){//为数据库添加子侦听器@Override公共无效onChildAdded(@NonNull DataSnapshot dataSnapshot,@Nullable String s){

© www.soinside.com 2019 - 2024. All rights reserved.