Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Java Admin SDK don't work

I am following the documentation on Firebase website on setting up an Java Admin SDK. So I add the dependency to the build.gradle, and added the following code:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseCredentials;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class Main {

    public static void main(String[] args) throws FileNotFoundException{
        FileInputStream serviceAccount = new FileInputStream("/Users/idanaviv10/Desktop/mapit-33290-firebase-adminsdk-fdy24-a1d0505493.json");

        FirebaseOptions options = new FirebaseOptions.Builder()
          .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
          .setDatabaseUrl("https://mapit-33290.firebaseio.com/")
          .build();

        FirebaseApp.initializeApp(options);
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("server/saving-data/fireblog");

        DatabaseReference usersRef = ref.child("users");

        Map<String, User> users = new HashMap<String, User>();
        users.put("alanisawesome", new User("June 23, 1912", "Alan Turing"));
        users.put("gracehop", new User("December 9, 1906", "Grace Hopper"));

        usersRef.setValue(users);
    }
    public static class User {

        public String date_of_birth;
        public String full_name;
        public String nickname;

        public User(String date_of_birth, String full_name) {
            // ...
        }

        public User(String date_of_birth, String full_name, String nickname) {
            // ...
        }

    }
}

The problem is when I am trying to get data (adding a listener) or trying to save data (like in the example) nothing happened. I am running the code in eclipse, I can see in the console that it print "Done", but when I check the database (on the firebase console on the browser) nothing change. enter image description here

like image 408
Idan Aviv Avatar asked Nov 21 '25 09:11

Idan Aviv


1 Answers

I found the problem, the problem was that the program will terminate before connecting to the Firebase server. What you need to do is to delay the termination of the program, by either calling Thread.sleep(20000);, or like I did it

Scanner scanner = new Scanner(System.in);
while(!scanner.nextLine().equals("Quit")){}
System.exit(0);  
like image 51
Idan Aviv Avatar answered Nov 24 '25 00:11

Idan Aviv