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"
}
}
感謝Doug,加入1秒的等待確實讓程序在退出前接收數據 - 並打印出「成功!」。信息。您是否有任何解決其他解決方案的策略/建議/資源? – caleb
Firebase中的異步操作返回一個Task對象。你可以學習如何使用這些。我從這裏開始了他們的一系列博客系列:https://firebase.googleblog.com/2016/09/become-a-firebase-taskmaster-part-1.html –