2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果userStatsDatabase指向此 JSON(對(duì)于特定用戶):
{
"August" : {
"Weight" : {
"Body_Fat" : "29",
"Month" : 8,
"Weight" : "68"
}
},
"October" : {
"Weight" : {
"Body_Fat" : "29",
"Month" : 10,
"Weight" : "67"
}
},
"September" : {
"Weight" : {
"Body_Fat" : "28.5",
"Month" : 9,
"Weight" : "65.5"
}
}
}
然后你可以按以下順序獲得結(jié)果Month:
Query query = userStatsDatabase..orderByChild("Weight/Month");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot monthSnapshot: dataSnapshot.getChildren()) {
System.out.println(monthSnapshot.getKey()); // August, September, October
System.out.println(monthSnapshot.child("Weight/Month").getValue(Long.class)); // 8, 9, 10
}
}
...

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
我放棄了使用 Firebase 查詢對(duì)數(shù)據(jù)進(jìn)行排序,我確信我的代碼沒有任何問題,無論如何,我決定使用 Collections.sort 將數(shù)據(jù)添加到 arrayList“之后”對(duì)其進(jìn)行排序,并且它有效。謝謝
PS,如果有人知道為什么我的 firebase 查詢不起作用,我仍然想知道原因:S
這是代碼,以防其他人需要對(duì) arrayList 中的數(shù)據(jù)進(jìn)行排序
//sort the item to show months in ascending order
Collections.sort(items, new Comparator<PastMonthsWeightStats>(){
@Override
public int compare(PastMonthsWeightStats obj1, PastMonthsWeightStats obj2) {
// ## Ascending order
// return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values
//return Float.valueOf(obj1.getMonthNumber()).compareTo(Float.valueOf(obj2.getMonthNumber())); // To compare integer values
// ## Descending order
// return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values
return Integer.valueOf(obj2.getMonthNumber()).compareTo(Integer.valueOf(obj1.getMonthNumber())); // To compare integer values
}
});
添加回答
舉報(bào)