2017-09-16 66 views
-3
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(); 

數組不返回查詢的值,但我爲初始化設置的值將幫助我做一個異步阻塞查詢某人可以幫助我?Firebase查詢幫助我

回答

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