gpt4 book ai didi

android - 从 Firebase 获取项目的位置

转载 作者:行者123 更新时间:2023-11-30 00:36:34 26 4
gpt4 key购买 nike

我找到了运行我的排行榜列表并返回相应值的代码。但我需要返回列表中项目的位置。我应该如何修改代码以使其返回项目的位置(索引)。

谢谢。

//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) {

}
});

enter image description here

最佳答案

我已经根据您的意见编辑了代码。由于您只关心位置和分数...

// 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com