2016-08-20 18 views
0

我想下面的代碼從我的服務器發送數據到火力在java中添加火力點:無法將數據從我的服務器使用Java

public class FirebaseManager { 
    public void configFirebase() throws FileNotFoundException{ 
     System.out.println("entered"); 
      FirebaseOptions options = new FirebaseOptions.Builder() 
        .setServiceAccount(new FileInputStream("/home/avy/Documents/avy-7ad6df4da352.json")) 
        .setDatabaseUrl("https://avy.firebaseio.com/") 
        .build(); 
      FirebaseApp firebaseApp = FirebaseApp.initializeApp(options); 

     final FirebaseDatabase database = FirebaseDatabase.getInstance(); 
     DatabaseReference reference = database.getReference("server/saving-data/fireblog"); 

     DatabaseReference postsRef = reference.child("posts"); 

     DatabaseReference newPostRef = postsRef.push(); 
     Task t = newPostRef.setValue(new Post("avy", "Announcing COBOL, a New Programming Language")); 
System.out.println(t.isComplete()); 
     postsRef.push().setValue(new Post("sam", "The Turing Machine")); 
    } 

    public static class Post { 

     public String author; 
     public String title; 

     public Post(String author, String title) { 
      this.author=author; 
      this.title=title; 
     } 

    } 

    public static void main(String args[]){ 
     try { 
      new FirebaseManager().configFirebase(); 
     } 
     catch (FileNotFoundException ex){ 
      System.out.println("File Not Found : /home/avy/Documents/avy-7ad6df4da352.json "); 
     } 
    } 

} 

但下面的代碼給了我假的。

Task t = newPostRef.setValue(new Post("avy", "Announcing COBOL, a New Programming Language")); 
System.out.println(t.isComplete()); 

請幫我找到這段代碼中的問題。 我想訪問Firebase數據庫來存儲我的帖子,以便它可以進一步傳送到移動設備。

回答

2

任務是異步對象,因此您的第二行代碼可能在任務完成之前運行。您是否檢查數據庫以查看帖子是否已添加?

如果是這樣你可以使用類任務的onCompleteListener知道什麼時候它就會完成

+0

我trried這樣的:'t.addOnCompleteListener(新執行官(){ @覆蓋 公共無效的execute(Runnable的命令) { 的System.out.println( 「執行......」);} } ,新OnCompleteListener(){ @覆蓋 公共無效的onComplete(@NonNull任務的任務){ 的System.out.println(t.isComplete ()); } }); 'onComplete事件不會執行 – avy

相關問題