我找到了运行我的排行榜列表并返回相应值的代码。但我需要返回列表中项目的位置。我应该如何修改代码以使其返回项目的位置(索引)。
谢谢。
//query for sorting by score
score = FirebaseDatabase.getInstance().getReference().child("Leaders");
final Query query = score.orderByChild("uID").equalTo(mCurrentUser.getUid());
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator();
int length = (int) dataSnapshot.getChildrenCount();
String[] sampleString = new String[length];
while(i < length) {
sampleString[i] = iterator.next().getValue().toString();
//Log.d(Integer.toString(i), sampleString[i]);
//print the value of current score
Toast.makeText(LeaderBoardActivity.this,sampleString[i],Toast.LENGTH_LONG).show();
i++;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
最佳答案
我已经根据您的意见编辑了代码。由于您只关心位置和分数...
// you will need to query the database based on scores
score = FirebaseDatabase.getInstance().getReference().child("Leaders");
final Query query = score.orderByChild("Score");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// get total leaders. Let's say total leader is 5 persons
int total = (int) dataSnapshot.getChildrenCount();
// let's say userB is actually 2nd in the list
int i = 0;
// loop through dataSnapshot
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String uID = childSnapshot.child("uID").getValue();
if (uID.equals(mCurrentUser.getUid()) {
// the list is ascending, when finally reach userB, i = 3
int userPlace = total - i; // gives 2
int score = childSnapshot.child("Score").getValue(Interger.class);
break;
} else {
i++;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
请注意,这可能会非常消耗带宽。随着您获得越来越多的用户,您将需要为每个查询下载所有用户数据。如果您只显示前 5 名领导者等,可能会更好。
关于android - 从 Firebase 获取项目的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43326389/