Firebase查询帮助我

时间:2017-09-16 09:40:30

标签: java firebase firebase-realtime-database nosql

final int[] ndomande = {14};

//Database
mFirebaseInstance = FirebaseDatabase.getInstance();

final DatabaseReference Refndom = mFirebaseInstance.getReference("Dati");
final Query queryn = Refndom.orderByChild("numero_domande");

queryn.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //Toast.makeText(PlayTest.this, "FIN QUI ",Toast.LENGTH_SHORT).show();

        for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
           // Toast.makeText(PlayTest.this, "QUI ",Toast.LENGTH_SHORT).show();

             long numero_domande = (long) messageSnapshot.getValue();
             ndomande[0] = (int) numero_domande;

            Toast.makeText(PlayTest.this, "quante domande ci sono totali: "+ numero_domande,Toast.LENGTH_SHORT).show();
        }

    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(PlayTest.this, "???", Toast.LENGTH_SHORT).show();
    }
});

//PROBLEM ON NDOMANDE 

Toast.makeText(PlayTest.this, "x: "+ ndomande[0] ,Toast.LENGTH_SHORT).show();
Random random = new Random();
final int x = random.nextInt(ndomande[0]);
 Toast.makeText(PlayTest.this, "x: "+ndomande[0] ,Toast.LENGTH_SHORT).show();

数组没有返回查询的值,但是我为初始化设置的值会帮助我做一个有人可以帮助我的异步阻塞查询吗?

1 个答案:

答案 0 :(得分:0)

要解决此问题,请将final int[] ndomande = {14};数组的声明移到onDataChange() method内,否则它将始终为空。

public void onDataChange(DataSnapshot dataSnapshot) {
    //Toast.makeText(PlayTest.this, "FIN QUI ",Toast.LENGTH_SHORT).show();
    final int[] ndomande = {14};

    for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
        //Toast.makeText(PlayTest.this, "QUI ",Toast.LENGTH_SHORT).show();

        long numero_domande = (long) messageSnapshot.getValue();
        ndomande[0] = (int) numero_domande;

        Toast.makeText(PlayTest.this, "quante domande ci sono totali: "+ numero_domande,Toast.LENGTH_SHORT).show();
    }
}

这是由于onDataChange() method的异步行为而发生的,即使您试图从该数组中获取值,也会调用它。在方法中移动声明并在那里使用它,解决了你的问题。

如果您想在该方法之外使用该数组的值,请查看我在这篇文章中的回答How To Get Async Value Outside onDataChange() Method