Firebase Query help me

末鹿安然 提交于 2019-12-14 00:08:59

问题


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:


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.



来源:https://stackoverflow.com/questions/46252420/firebase-query-help-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!