Firebase Query help me

2019-09-21 21:45发布

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();

the array does not return the value of the query but the value I set for initialization would help me make an asynchronous blocking query someone can help me?

1条回答
闹够了就滚
2楼-- · 2019-09-21 22:10

To solve this problem, move the declaration of your final int[] ndomande = {14}; array inside the onDataChange() method, otherwise it will be always null.

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();
    }
}

This is happening due the asynchronous behaviour of onDataChange() method, which is called before even you are trying to get the value from that array. Moving the declaration inside the method and using it also there, solves your problem.

If you want to use the value of that array outside that method, please take a look at my answer from this post, How To Get Async Value Outside onDataChange() Method.

查看更多
登录 后发表回答