0

我正在尝试制作用于编辑 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获得此代码

4

0 回答 0