简体   繁体   中英

Connecting to firestore from spring boot application throws a null pointer exception

Hi I am trying to connect the google cloud firestore to spring boot app to retrieve some data but I constantly get the same error. I have checked setting the GOOGLE_CREDENTIALS variable in the environment but no luck. Any help is appreciated. Thanks in advance.

Service class code

 public TrainInfo getTrainInfo(String trainId) throws InterruptedException, ExecutionException{
                Firestore db=FirestoreOptions.getDefaultInstance().getService();
                DocumentReference docRef = db.collection(COLUMN).document(trainId);
                ApiFuture<DocumentSnapshot> future = docRef.get();
                DocumentSnapshot document = future.get();
        
                TrainInfo trainInfo=null;
        
                if (document.exists()) {
                    // convert document to POJO
                    trainInfo = document.toObject(TrainInfo.class);
        
                } else {
                    System.out.println("No such document!");
                }
                return trainInfo;
            }

Error displaying

  java.lang.NullPointerException: null
        at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:892) ~[guava-30.1.1-android.jar:na]
        at com.google.firestore.v1.DatabaseRootName.<init>(DatabaseRootName.java:56) ~[proto-google-cloud-firestore-v1-2.3.0.jar:2.3.0]
        at com.google.firestore.v1.DatabaseRootName.<init>(DatabaseRootName.java:29) ~[proto-google-cloud-firestore-v1-2.3.0.jar:2.3.0]
        at com.google.firestore.v1.DatabaseRootName$Builder.build(DatabaseRootName.java:157) ~[proto-google-cloud-firestore-v1-2.3.0.jar:2.3.0]
        at com.google.firestore.v1.DatabaseRootName.of(DatabaseRootName.java:61) ~[proto-google-cloud-firestore-v1-2.3.0.jar:2.3.0]
        at com.google.cloud.firestore.spi.v1.GrpcFirestoreRpc.<init>(GrpcFirestoreRpc.java:111) ~

Setting the credentials from the environment didnt work for me so I did it from the code itself like below:
Credentials credentials = GoogleCredentials.fromStream(new FileInputStream("/pathtojsonfile")); FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder().setProjectId(PROJECT_ID).setCredentials(credentials).build();

Might help someone !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM