【发布时间】:2020-07-18 17:35:51
【问题描述】:
我想创建一个高分 ListView,条目按降序显示,使用 orderByValue 我将它们按升序排序,但是当我的 arraylist 使用 Collections.reverse() 时,条目仍然没有反转列表视图。
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 来解决这个问题,所有其他元素都简单地向右移动,导致按降序排列的列表视图。
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
【问题讨论】:
-
请编辑您的问题以在您的数据库中显示
Highscores的数据(作为文本,请不要截图)。您可以通过单击 Firebase Database console 的溢出菜单 (⠇) 中的“导出 JSON”链接来获取此信息。 -
请检查副本以了解如何按降序排列结果。
标签: java android sorting firebase-realtime-database leaderboard