gpt4 book ai didi

java - Firebase 数据顺序

转载 作者:行者123 更新时间:2023-12-02 11:38:56 25 4
gpt4 key购买 nike

我有一个类,如下所示:

public class GlobalHighScore {
String name;
int score;

public GlobalHighScore(String name, int score) {
this.name = name;
this.score = score;
}


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getScore() {
return score;
}

public void setScore(int score) {
this.score = score;
}
}

这里我尝试进行数据接收。

DatabaseReference scoresRef = firebaseDatabase.getReference("Highscores");    
scoresRef.child("GlobalHighScore").orderByChild("score").limitToFirst(10);
scoresRef.addValueEventListener(new ValueEventListener() {
@Override public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> keys = dataSnapshot.getChildren();
int i = 0;
for (DataSnapshot key : keys) {
if(i == 10)
break;
orderName[i].setText(key.getValue().toString());
i++;
}
}

当我这样做时,key.getValue().toString()返回json格式的字符串,但我想要单独的“name”和“score”。另外,即使我进行了排序,我的数据也没有排序。

scoresRef.child("GlobalHighScore").orderByChild("score").limitToFirst(10);

我想我这里有问题。

编辑:当我按“分数”排序时,它会根据日期提供数据。

最后一个表格是

 final TextView[] orderScore = {firstscore, secondscore, thirdscore, fourthscore, fifthscore, sixthscore, seventhscore, eightscore, ninthscore, tenthscore};
final TextView[] orderName = {firstname, secondname, thirdname, fourthname, fifthname, sixthname, seventhname, eightname, ninthname, tenthname};

DatabaseReference scoresRef = firebaseDatabase.getReference("Highscores").child("GlobalHighScore");
scoresRef.orderByChild("score").limitToFirst(10);
scoresRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot data : dataSnapshot.getChildren()) {
if(i == 10)
break;
String name = data.child("name").getValue().toString();
String score = data.child("score").getValue().toString();
orderName[i].setText(name);
orderScore[i].setText(score);
i++;
}
}

它根本没有提供任何数据记录。

最佳答案

试试这个:

 DatabaseReference scoresRef = firebaseDatabase.getReference("Highscores").child("GlobalHighScore");
Query q=scoresRef.orderByChild("score").limitToFirst(10);
q.addValueEventListener(new ValueEventListener() {
@Override public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()){
String name=datas.child("name").getValue().toString();
String score=datas.child("score").getValue().toString();
}
}

由于您只想要名称和分数,因此您可以执行上述操作,以便能够单独检索它们。

.orderByChild("score").limitToFirst(10);,使用它您将获得前 10 个具有子 score 的节点。

limitToFirst(10)//获取特定子项的前 10 个

limitToLast(10)//获取特定子项的最后 10 个

关于java - Firebase 数据顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48720030/

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