2017-02-10 71 views
0

我試圖通過Java從Firebase讀取數據。 addListenerForSingleValueEvent以及我放入它的任何東西都不會執行。在搜索其他相關的堆棧問題後,我一直無法找到與Android無關的答案。請看一下,讓我知道爲什麼這個方法沒有執行。提前致謝。addListenerForSingleValueEvent不執行

import com.google.firebase.FirebaseApp; 
import com.google.firebase.FirebaseOptions; 
import com.google.firebase.database.DatabaseReference; 
import com.google.firebase.database.DataSnapshot; 
import com.google.firebase.database.DatabaseError; 
import com.google.firebase.database.FirebaseDatabase; 
import com.google.firebase.database.ValueEventListener; 
import java.io.*; 

public class App { 

    public static void main(String[] args) { 

     class ServiceFile { 

      private FileInputStream mMyFile; 

      public ServiceFile(String myFile) { 
       try { 
        mMyFile = new FileInputStream(myFile); 
        System.out.println("The Service File exists. "); // this line prints 
       } catch (FileNotFoundException ex) { 
        System.out.println("The Service File does not exist."); 
       } 
      } 

      public FileInputStream getMyFile() { 
       return mMyFile; 
      } 
     } 

     ServiceFile serviceFile = new ServiceFile("/Users/xxxx/Documents/development/javaFire/serviceAccountKey.json"); 

     FirebaseOptions options = new FirebaseOptions.Builder() 
       .setServiceAccount(serviceFile.getMyFile()) 
       .setDatabaseUrl("https://xxxx.firebaseio.com") 
       .build(); 

     // Initialize the app 
     FirebaseApp myApp = FirebaseApp.initializeApp(options); 

     // Get the reference to some location within the DB 
     final FirebaseDatabase database = FirebaseDatabase.getInstance(myApp); 
     DatabaseReference ref = database.getReference("https://stackoverflow.com/users/john"); 

     // Attach a listener to read the data at the DB reference 
     ref.addListenerForSingleValueEvent(new ValueEventListener() { 

      @Override 
      public void onDataChange(DataSnapshot theData) { 
       System.out.println("Success! "); // this line does not print 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 
       System.out.println("Cancelled" + databaseError.getMessage()); // this line does not print 
      } 
     }); 

    } 

} 

我的數據庫規則是這樣:

{ 
    "rules": { 
    ".read": true, 
    ".write": "auth != null" 
    } 
} 

我在火力地堡數據,在/users.json

{ 
    "john": { 
    "dob": "02/20/1980" 
    } 
} 

回答

0

它看起來像你的回調沒有執行,因爲你的程序結束在回調之前可以接收新數據。請記住,addListenerForSingleValueEvent是異步的(它立即返回),所以您的主函數將立即返回,這意味着JVM將退出。

至少可以在函數末尾調用Thread.sleep()以確保它不會立即終止。但對於一個真正的計劃,你可能會做其他事情。

+0

感謝Doug,加入1秒的等待確實讓程序在退出前接收數據 - 並打印出「成功!」。信息。您是否有任何解決其他解決方案的策略/建議/資源? – caleb

+0

Firebase中的異步操作返回一個Task對象。你可以學習如何使用這些。我從這裏開始了他們的一系列博客系列:https://firebase.googleblog.com/2016/09/become-a-firebase-taskmaster-part-1.html –