Firebase Java Admin SDK don't work

醉酒当歌 提交于 2020-01-23 02:46:27

问题


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.


回答1:


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



回答2:


One other thing you can try is to explicitly wait until the setValue() task is complete using the Tasks API:

Task<Void> task = usersRef.setValue(users);
try {
    Tasks.await(task);
} catch (ExecutionException | InterruptedException e) {
    // Handle error if necessary
}



回答3:


below code is pushing data into firebase database using java async call api from firebase sdk but listeners code is not executing . I am running below code in server side backend.

 public enum Firebase {
INSTANCE;

FirebaseApp firebaseApp;


public void initilizeFirebaseApp(ConfigLoader configReader) {

    CountDownLatch done = new CountDownLatch(1);
    final AtomicInteger message1 = new AtomicInteger(0);
    InputStream firebaseSecret = getClass().getClassLoader().getResourceAsStream("ServiceAccount.json");
    final GoogleCredentials credentials;
    try {
        credentials = GoogleCredentials.fromStream(firebaseSecret);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error while reading Firebase config file." + e.toString());
        throw new IllegalStateException(e);
    }

    Map<String, Object> auth = new HashMap<>();
    auth.put("uid", "my_resources");

    FirebaseOptions options = new Builder()
            .setConnectTimeout(1000)
            .setCredentials(credentials)
            .setDatabaseAuthVariableOverride(auth)
            .setDatabaseUrl(configReader.getFirebaseDatabaseURL())
            .setStorageBucket(configReader.getFirebaseStorageBucket())
            .setProjectId(configReader.getFirebseProjectId())
            .build();

    firebaseApp = FirebaseApp.initializeApp(options);


    System.out.println(firebaseApp.getName());
    //System.out.println(firebaseApp.getName());
    // Use the shorthand notation to retrieve the default app's service
    FirebaseAuth defaultAuth = FirebaseAuth.getInstance();
    FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();


    // The app only has access as defined in the Security Rules
    DatabaseReference ref = FirebaseDatabase
            .getInstance()
            .getReference("/analyst_profiles");


    DateTime dt = new DateTime(java.util.Date.from(Instant.now()), java.util.TimeZone.getDefault());
    System.out.println(dt.getValue());
    //test data push
    // https://firebase.google.com/docs/database/admin/save-data
    AnalystProfiles analystProfilesObjTemp = new AnalystProfiles("test2", Long.toString(dt.getValue()), "dsds", "ds", "ds",
            "dsa2323", "32ddss232");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            AnalystProfiles post = dataSnapshot.getValue(AnalystProfiles.class);
            System.out.println(post);
            //done.countDown();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());
        }


    });


    CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {
        try {
            ref.push().setValueAsync(analystProfilesObjTemp).get();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException("Error while waiting for future", e);
        }
        return "ok";

    }).thenApply(x -> {
        System.out.println(x);
        System.out.println("Listeners code is not executing");
        return x;
    });


    done.countDown();
    try {
        System.out.println(welcomeText.get());
        done.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }


}


public void testdataLoad() {

    // The app only has access as defined in the Security Rules
    DatabaseReference ref = FirebaseDatabase
            .getInstance()
            .getReference("/analyst_profiles");


    DateTime dt = new DateTime(java.util.Date.from(Instant.now()), java.util.TimeZone.getDefault());
    System.out.println(dt.getValue());
    //test data push
    // https://firebase.google.com/docs/database/admin/save-data
    AnalystProfiles analystProfilesObjTemp = new AnalystProfiles("test2", Long.toString(dt.getValue()), "dsds", "ds", "ashutsh",
            "dsa2323", "32ddss232");

    CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {
        try {
            ref.push().setValueAsync(analystProfilesObjTemp).get();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException("Error while waiting for future", e);
        }
        return "ok";

    }).thenApply(x -> {
        System.out.println(x);
        return x;
    });



    try {
        System.out.println(welcomeText.get());

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

}

}




回答4:


Add this code:

ApiFuture api=/*your reference to database*/usersRef.setValueAsync(users/*the data*/);

Object o = api.get(/*time out*/8,TimeUnit.SECONDS/*unite for time out her is seconds*/);

And at last you can check with

api.isDone();



来源:https://stackoverflow.com/questions/43693797/firebase-java-admin-sdk-dont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!