我创建了firebase项目,并且它从android应用程序中正常工作。然后我尝试将相同的firebase应用程序集成到我的API中。我按照Firebase网站上的文档设置了Java Admin SDK。
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
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.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewClass {
public static void main(String[] args) {
FileInputStream serviceAccount = new FileInputStream(".\Signage-f5d7a18d6c2c.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://signage-7068e.firebaseio.com/")
.build();
FirebaseApp initializeApp = FirebaseApp.initializeApp(options);
System.out.println("-start-");
System.out.println(initializeApp.getName());
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(FirebaseApp.getInstance());
defaultDatabase.getReference().child("Client").child("-KkOvAIiASpGaNgzI4Go").getRef().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("onDataChange");
}
@Override
public void onCancelled(DatabaseError error) {
System.out.println("onCancelled");
}
});
System.out.println(defaultDatabase.getReference().child("Client").push().getKey());
System.out.println("-end-");
}
}
我的输出是:
-start-
[DEFAULT]
-Kx7lHj7G0wem7R29E7G
-end-
似乎正确建立了与数据库的连接,因为getKey()
方法生成了一个新密钥。但是ValueEventListeners
没有触发。我也宣布了规则。
{
"rules": {
"Client":{
".read": "true",
".write": "true"
}
}