Firebase Admin数据库无法读取

时间:2017-04-04 18:26:25

标签: java firebase firebase-realtime-database firebase-admin

我正在尝试制作用于编辑firebase数据库的桌面应用。我是用java语言编写的,但我无法使用数据库。

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.auth.FirebaseCredentials;

public class MainClass {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        FileInputStream serviceAccount = new FileInputStream("adminkey.json");


        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                .setDatabaseUrl("https://<database name>.firebaseio.com")
                .build();
        FirebaseApp app = FirebaseApp.initializeApp(options);

        System.out.println(app.getName());

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                System.out.println("Database works");
                Iterable<DataSnapshot> td = dataSnapshot.getChildren();
                if(dataSnapshot.hasChildren())
                    System.out.println("Have childrens");
                for(DataSnapshot key : td){
                String document = key.getKey();
                System.out.println(document);
                }
            }

            @Override
            public void onCancelled(DatabaseError arg0) {
                // TODO Auto-generated method stub
                System.out.println("Cancel");
            }
        }); 
    }    
}

当我运行此代码时,它没有写入控制台“数据库工作”或“已取消”。它永远不会进入onDataChange()或onCanceled()。

我从https://firebase.google.com/docs/database/admin/start

获取此代码

0 个答案:

没有答案