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