如何从firebase中检索int

时间:2017-09-20 19:36:43

标签: android firebase firebase-realtime-database

 private void updateScoreBreaker(){
    DBref=FirebaseDatabase.getInstance().getReference().child(Gamelevel);
    Query maxScore =DBref.orderByChild(SCORE).limitToLast(1);
    maxScore.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
         maxScoreLevel=Integer.parseInt(dataSnapshot.child(SCORE).getValue(String.class));
              maxScoreName=dataSnapshot.getKey();
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

我有这个错误: 无法找到本地变量" maxScoreLevel'

1 个答案:

答案 0 :(得分:3)

好像你还没有声明 maxScoreLevel 。您应该将其声明为类的属性,以便可以从ValueEventListener更改它的值。

class something {
    ...
    Integer maxScoreLevel;
    String maxScoreName;
    ...

    private void updateScoreBreaker() {
        DBref = FirebaseDatabase.getInstance().getReference().child(Gamelevel);
        Query maxScore = DBref.orderByChild(SCORE).limitToLast(1);
        maxScore.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                maxScoreLevel = dataSnapshot.child(SCORE).getValue(Integer.class);
                maxScoreName = dataSnapshot.getKey();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }
}

如果相应的引用不存在或没有值,则将为maxScoreLevel分配 null