[英]Get information from Firebase Realtime Database with Firebase Admin SDK
I'm trying to get some information from Firebase Real-time database without success. 我试图从Firebase实时数据库中获取一些信息但没有成功。 I don't know what I'm doing wrong. 我不知道我做错了什么。 I also tried the doc's example and they didn't work. 我也尝试了doc的例子但它们没有用。 Here's my code and my firebase db structue: 这是我的代码和我的firebase db结构:
Topics.java: Topics.java:
public class Topics {
private String name;
public Topics() {
}
public Topics(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Main.java Main.java
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream serviceAccount;
FirebaseOptions options = null;
try {
serviceAccount = new FileInputStream(".//...");
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("...")
.build();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
String topics = getDatafromFirebase();
System.out.println("Everything right!");
}
private static String getDatafromFirebase() {
CountDownLatch done = new CountDownLatch(1);
StringBuilder b = new StringBuilder();
DatabaseReference dbRef = FirebaseDatabase.getInstance()
.getReference();
dbRef.child("topics").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
if(snapshot.exists()) {
for(DataSnapshot s:snapshot.getChildren()) {
Topics t = s.getValue(Topics.class);
b.append(t.getName());
b.append(" ");
done.countDown();
}
}
else {
b.append("No existe ");
done.countDown();
}
}
@Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
b.append("Error: "+error.getDetails());
done.countDown();
}
});
try {
done.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b.toString();
}
I have wait for the CountDownLatch
for 5+
minutes, which I think is enough time for it to trigger. 我等待CountDownLatch
超过5+
分钟,我认为它足以触发它。 Also, important note: I have successfully sent message through firebase cloud messaging, so I don't think that it is a problem with the credentials. 另外,重要提示:我已成功通过firebase云消息传递消息,因此我认为这不是凭据的问题。
I ran your code against my database with the same db structure and I can for sure say that I am ableto get information from the database. 我使用相同的数据库结构对我的数据库运行代码,我可以肯定地说我能够从数据库中获取信息。
onDataChange
breakpoint not triggering only happens if I remove the topics
subtree entirely. 如果我完全删除topics
子树,则仅触发onDataChange
断点。 ie. 即。 in your case an empty database. 在你的情况下一个空的数据库。
I suspect either your database url or Private Key JSON. 我怀疑你的数据库网址或私钥JSON。
In the console, click the gear icon on the left, and the Service Accounts Tab Refer 在控制台中,单击左边的齿轮图标 ,并在服务帐户选项卡请参阅
Take a note of databaseUrl and click on Generate New Private Key , save it. 记下databaseUrl并单击Generate New Private Key ,保存它。 Refer 参考
package fireb;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import com.google.auth.oauth2.GoogleCredentials;
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;
public class Fireb {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream serviceAccount;
FirebaseOptions options = null;
try {
serviceAccount = new FileInputStream("C:\\key\\testapp-f0fe2-firebase-adminsdk-4po4a-5ce6c60b81.json");
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://testapp-f0fe2.firebaseio.com")
.build();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
String topics = getDatafromFirebase();
System.out.println(topics);
System.out.println("Everything right!");
}
private static String getDatafromFirebase() {
CountDownLatch done = new CountDownLatch(1);
StringBuilder b = new StringBuilder();
DatabaseReference dbRef = FirebaseDatabase.getInstance()
.getReference();
dbRef.child("topics").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
if(snapshot.exists()) {
for(DataSnapshot s:snapshot.getChildren()) {
Topics t = s.getValue(Topics.class);
b.append(t.getName());
b.append(" ");
}
done.countDown();
}
else {
b.append("No existe ");
done.countDown();
}
}
@Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
b.append("Error: "+error.getDetails());
done.countDown();
}
});
try {
done.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b.toString();
}
}
According to the documentation available here . 根据这里提供的文件。
Before you can access the Firebase Realtime Database from a server using the Firebase Admin SDK, you must authenticate your server with Firebase. 在使用Firebase Admin SDK从服务器访问Firebase实时数据库之前,您必须使用Firebase对服务器进行身份验证。 When you authenticate a server, rather than sign in with a user account's credentials as you would in a client app, you authenticate with a service account which identifies your server to Firebase. 在对服务器进行身份验证时,不是像在客户端应用中那样使用用户帐户的凭据登录,而是使用服务帐户进行身份验证,该帐户会将您的服务器标识为Firebase。
If you are not running your code on server, you may authenticate as a client instead as described here . 如果您没有在服务器上运行代码,则可以将此身份验证为客户端,而不是此处所述。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.