现在,我有一个排行榜,应用程序使用我在Firebase中生成的假播放器显示,如下所示:
我想知道如何将每一个玩我的应用的新玩家的名字添加到排行榜中。
现在,我的代码手动吸引了每个假玩家,而且我没有自动方法来吸引n个玩家进入
user2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value_temp = dataSnapshot.getValue(String.class);
if(value_temp != null)
workshopParticipants.add(new LeaderPlayers(value_temp));
Collections.sort(workshopParticipants);
//Log.d(TAG, "Value is: " + mHigh);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
//Log.w(TAG, "Failed to read value.", error.toException());
}
});
user3 = database.getReference(Integer.toString(3));
user3.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value_temp = dataSnapshot.getValue(String.class);
Log.d(TAG, value_temp);
if(value_temp != null)
workshopParticipants.add(new LeaderPlayers(value_temp));
Collections.sort(workshopParticipants);
//Log.d(TAG, "Value is: " + mHigh);
for(int a = 0; a < workshopParticipants.size(); a++)
{
players.add(workshopParticipants.get(a).getFullName());
}
for(int a = 0; a < players.size(); a++){
Log.d(TAG, "Players are: " + players.get(a));
}
}
这是我手动添加假玩家的方式。
它目前适用于假玩家,但是如果我有N个真正的玩家在玩我的游戏,那么我希望所有N个玩家也出现在排行榜上。
答案 0 :(得分:1)
如果我对您的理解正确,则希望加载所有用户,而不必分别加载每个用户。您可以通过在树中将侦听器附加上一层,然后遍历子节点来实现此目的:
database.getReference().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, userSnapshot.getKey()); // "1", "2"...
Log.d(TAG, userSnapshot.getValue(String.class)); "Christine 20", "Tom 64"...
}
}
@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException()); // Don't ignore errors
}
});