如果我做对了,有人能看到吗?从 firebase 数据库我正在使用这个获取我的数据
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference()
.child("Users").child("Displayname")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Map<String, Object> map =(Map<String, Object>) snapshot.getValue();
for (Map.Entry<String, Object> entry : map.entrySet()){
Cred = (String) entry.getValue();
friend = snapshot.getKey();
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
并使用这个放置到字符串数组中
List<String> list = new ArrayList<String>();
list.add(Cred+" "+friend);
String[] stringArray = list.toArray(new String[0]);
通过使用下面的代码,我想将它降序排列
Comparator comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String num1 = o1.split(" ")[0];
String num2 = o2.split(" ")[0];
return Integer.parseInt(num2) - Integer.parseInt(num1);
}
};
Arrays.sort(stringArray, comparator);
System.out.println(Arrays.toString(stringArray));
但我没有得到我的结果:
Expected result :
"300.0 Baul",
"4.0 Alex",
"1.0 Lex B05"
My system print out:
2019-12-23 15:17:02.285 752-752/com.seamans.marina I/System.out: [4.0 Alex]
2019-12-23 15:17:02.292 752-752/com.seamans.marina I/System.out: [300.0 Baul]
2019-12-23 15:17:02.296 752-752/com.seamans.marina I/System.out: [1.0 Lex B05]
我的 firebase 数据库:
最佳答案
尝试用这种方式排序
Collections.sort(stringArray, (c1, c2) -> {
String num1 = c1.split(" ")[0];
String num2 = c2.split(" ")[0];
return Double.compare(Double.parseDouble(num2), Double.parseDouble(num1));
});
System.out.println(stringArray);
更新 1:用上面的内容替换此 block
Comparator comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String num1 = o1.split(" ")[0];
String num2 = o2.split(" ")[0];
return Integer.parseInt(num2) - Integer.parseInt(num1);
}
};
Arrays.sort(stringArray, comparator);
System.out.println(Arrays.toString(stringArray));
关于java - firebase 数据库到自定义 ListView 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451481/