[英]Get the position of item from Firebase
我找到了通過我的排行榜列表運行並返回相應值的代碼。 但我需要返回列表中項目的位置。 我應該如何修改代碼以便它返回項目的位置(索引)。
謝謝。
//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 名領導者等可能會更好。
我使用以下方法按位置更改子值,希望這可以給您一些幫助:
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++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.