Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get information from Firebase Realtime Database with Firebase Admin SDK

I'm trying to get some information from Firebase Real-time database without success. I don't know what I'm doing wrong. I also tried the doc's example and they didn't work. Here's my code and my firebase db structue:

Database structure

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

I have wait for the CountDownLatch for 5+ minutes, which I think is enough time for it to trigger. 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.

like image 984
Emmanuel Guerra Avatar asked Oct 13 '18 16:10

Emmanuel Guerra


1 Answers

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. ie. in your case an empty database.

I suspect either your database url or Private Key JSON.

Follow the below Instruction for a new private key

  1. In the console, click the gear icon on the left, and the Service Accounts Tab Refer

  2. Take a note of databaseUrl and click on Generate New Private Key, save it. Refer

Here is the working code for example

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();
    }
}
like image 162
Jaikanth J Avatar answered Nov 14 '22 06:11

Jaikanth J