簡體   English   中英

使用Firebase Admin SDK從Firebase實時數據庫獲取信息

[英]Get information from Firebase Realtime Database with Firebase Admin SDK

我試圖從Firebase實時數據庫中獲取一些信息但沒有成功。 我不知道我做錯了什么。 我也嘗試了doc的例子但它們沒有用。 這是我的代碼和我的firebase db結構:

數據庫結構

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

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();
}

我等待CountDownLatch超過5+分鍾,我認為它足以觸發它。 另外,重要提示:我已成功通過firebase雲消息傳遞消息,因此我認為這不是憑據的問題。

我使用相同的數據庫結構對我的數據庫運行代碼,我可以肯定地說我能夠從數據庫中獲取信息。

如果我完全刪除topics子樹,則僅觸發onDataChange斷點。 即。 在你的情況下一個空的數據庫。

我懷疑你的數據庫網址或私鑰JSON。

按照以下說明獲取新的私鑰

  1. 在控制台中,單擊左邊的齒輪圖標 ,並在服務帳戶選項卡請參閱

  2. 記下databaseUrl並單擊Generate New Private Key ,保存它。 參考

這是工作代碼,例如

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();
    }
}

根據這里提供的文件。

在使用Firebase Admin SDK從服務器訪問Firebase實時數據庫之前,您必須使用Firebase對服務器進行身份驗證。 在對服務器進行身份驗證時,不是像在客戶端應用中那樣使用用戶帳戶的憑據登錄,而是使用服務帳戶進行身份驗證,該帳戶會將您的服務器標識為Firebase。

如果您沒有在服務器上運行代碼,則可以將此身份驗證為客戶端,而不是此處所述。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM