侦听器不适用于java中的firebase datareference

侦听器不适用于java中的firebase datareference,java,firebase,firebase-realtime-database,Java,Firebase,Firebase Realtime Database,我正在尝试连接我的firebase数据库并从那里获取JSON结构。 但是我的ref(引用变量)中的侦听器不工作。我想该程序会连接到Firebase控制台,但它不会获取我认为的任何内容,因为侦听器不工作。 onDataChanged或onCancelled方法均无效。 如果我没有记错,Java程序将在不等待加载数据的情况下退出。您必须使用一些Java同步原语显式地使其等待,例如: import com.google.auth.oauth2.GoogleCredentials; import com

我正在尝试连接我的firebase数据库并从那里获取JSON结构。 但是我的ref(引用变量)中的侦听器不工作。我想该程序会连接到Firebase控制台,但它不会获取我认为的任何内容,因为侦听器不工作。 onDataChanged或onCancelled方法均无效。

如果我没有记错,Java程序将在不等待加载数据的情况下退出。您必须使用一些Java同步原语显式地使其等待,例如:

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.*;
import com.google.gson.Gson;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Logger
/**
*
* @author adnan
*/
public class Json_Reader {

private final static Logger log
        = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

public static void intializeFirebase() throws FileNotFoundException, IOException {

    FileInputStream serviceAccount =
            new FileInputStream("/home/adnan/Downloads/cryleticstest-firebase-adminsdk-avbul-f5ea5a09ca.json");

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://cryleticstest.firebaseio.com")
            .build();

    FirebaseApp.initializeApp(options);

    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    System.out.println(FirebaseApp.getApps());
    DatabaseReference ref = database.getReference();
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            System.out.println(dataSnapshot.getChildrenCount());
            Object object = dataSnapshot.getValue(Object.class);
            String json = new Gson().toJson(object);
            log.info(json);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            log.info("error");

        }
    });


}


public static void main(String[] args) throws IOException {

    intializeFirebase();

}
 }
另见:


回答得很好!谢谢
final CountDownLatch sync = new CountDownLatch(1);

DatabaseReference ref = database.getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        System.out.println(dataSnapshot.getChildrenCount());
        Object object = dataSnapshot.getValue(Object.class);
        String json = new Gson().toJson(object);
        log.info(json);
        sync.countDown();
    }

    @Override
    public void onCancelled(DatabaseError error) {
        log.info("error");
        sync.countDown();
    }
});

sync.await();