2017-02-10 37 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 –