我找到了通过我的排行榜列表运行的代码并返回相应的值。但我需要返回列表中项目的位置。我应该如何修改代码,以便返回项目的位置(索引)。
感谢。
//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) {
}
});
答案 0 :(得分:1)
我已根据您的评论编辑了代码。既然你只关心职位和得分......
// 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位领导等等,可能会更好。
答案 1 :(得分:0)
我使用以下方法按位置更改子级值,希望这对您有所帮助:
DataSnapshot targetData;
@Override
protected void onStart() {
super.onStart();
targetReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshots) {
targetData = dataSnapshots; //save in global variable
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void yourMethod() {
int index = 0;
for (DataSnapshot childSnapshot : targetData.getChildren()) {
if (index == 1) { //your target index
DatabaseReference currentReference = childSnapshot.getRef();
currentReference.setValue("xxx");
}
index++;
}
}