2016-05-17 121 views
0

我正在做一個項目,現在應該是一個數學教學應用程序的孩子。 我使用firebase作爲我的數據庫來保存用戶名和密碼,並保存問題和答案。 我有一個問題,從數據庫中提取問題和答案,並將其顯示在按鈕和textview上,因爲它顯示只有當類完成所有其他命令時纔會觸發單值事件的偵聽器,而且我需要使用這是我聽到的每個問題的聽衆。android firebase檢索數據不止一次

我的數據庫: enter image description here

到目前爲止我的代碼:

ArrayList <Integer> list = new ArrayList<Integer>(); 
    for (int i=1; i<11; i++) { 
     list.add(new Integer(i)); 
    } 
    Collections.shuffle(list); 

    for (int i=0; i<5; i++) { 
     ref2 = ref.child(list.get(i).toString()); 
     Questions.cont = false; 
     getQuestionsFromDb(ref2); 

     questionView.setText(Questions.question); 
     button1.setText(Questions.ans1); 
     button2.setText(Questions.ans2); 
     button3.setText(Questions.ans3); 
     button4.setText(Questions.ans4); 

     button1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       Questions.cont = true; 
       int ans = getAns(Questions.question); 
       Button b = (Button)v; 
       int buttonText = Integer.parseInt(b.getText().toString()); 
       if(ans == buttonText) { 
        Questions.points++; 
       } 
      } 
     }); 
      } 
     questionView.setText(Questions.points); 

     // end of for loop 
    } 
private void getQuestionsFromDb(Firebase ref2) { 
    // TODO Auto-generated method stub 

    ref2.addListenerForSingleValueEvent(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot snapshot) { 
     System.out.println("aaa"); 
      String question = (String) snapshot.child("question").getValue(); 
      String ans1 = snapshot.child("ans1").getValue().toString(); 
      String ans2 = snapshot.child("ans2").getValue().toString(); 
      String ans3 = snapshot.child("ans3").getValue().toString(); 
      String ans4 = snapshot.child("ans4").getValue().toString(); 
      Questions.question = question; 
      Questions.ans1 = ans1; 
      Questions.ans2 = ans2; 
      Questions.ans3 = ans3; 
      Questions.ans4 = ans4; 
     } 
     @Override 
     public void onCancelled(FirebaseError arg0) { 
      // TODO Auto-generated method stub 
     } 
    }); 
} 

private int getAns(String ansString) { 
    // TODO Auto-generated method stub 
    String[] parts = ansString.split("\\b"); 
    String ans; 
    if(parts.length == 5) { 
     ans = parts[0] + parts[1] + parts[2] + parts [3] + parts [4]; 
    } 
    else { 
     ans = parts[0] + parts[1] + parts[2]; 
    } 
    return Integer.parseInt(ans); 
} 

正如你可以看到我還使用具有靜態變量,用以保存的問題和答案外部類和把它們用於內部課堂。

我希望有人能幫忙。

+0

歡迎來到奇妙的異步編程世界。由於所有的firebase函數都是異步的,這意味着程序的其餘部分不會等待它完成。看看[這個答案](http://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener/33204705#33204705) –

+0

什麼是問題? –

回答

0

在你的情況下,你應該添加更多的偵聽器addListenerForSingleValueEvent()來獲得你需要的所有數據或者使用addValueEventListener重寫你的邏輯。在這種情況下,您的數據在任何時候都是實際的。