質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Firebase

Firebaseは、Googleが提供するBasSサービスの一つ。リアルタイム通知可能、並びにアクセス制御ができるオブジェクトデータベース機能を備えます。さらに認証機能、アプリケーションのログ解析機能などの利用も可能です。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Q&A

解決済

1回答

724閲覧

Firebase Firestore と Javaとの連携について

kuroishi

総合スコア53

Firebase

Firebaseは、Googleが提供するBasSサービスの一つ。リアルタイム通知可能、並びにアクセス制御ができるオブジェクトデータベース機能を備えます。さらに認証機能、アプリケーションのログ解析機能などの利用も可能です。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

0グッド

0クリップ

投稿2020/05/19 10:28

お世話になっております。
今回、表題の件に関しまして質問させていただきます。

package firebase.sample; import java.io.FileInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; /* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.api.core.ApiFuture; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.DocumentReference; // [START fs_include_dependencies] import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreOptions; // [END fs_include_dependencies] import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.firestore.WriteResult; import com.google.common.collect.ImmutableMap; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; /** * A simple Quick start application demonstrating how to connect to Firestore * and add and query documents. */ public class Quickstart { private Firestore db; /** * Initialize Firestore using default project ID. */ public Quickstart() { // [START fs_initialize] Firestore db = FirestoreOptions.getDefaultInstance().getService(); // [END fs_initialize] this.db = db; } public Quickstart(String projectId) { // [START fs_initialize_project_id] FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder() .setProjectId(projectId) .build(); Firestore db = firestoreOptions.getService(); // [END fs_initialize_project_id] this.db = db; } Firestore getDb() { return db; } /** * Add named test documents with fields first, last, middle (optional), born. * * @param docName document name */ void addDocument(String docName) throws Exception { switch (docName) { case "alovelace": { // [START fs_add_data_1] DocumentReference docRef = db.collection("users").document("alovelace"); // Add document data with id "alovelace" using a hashmap Map<String, Object> data = new HashMap<>(); data.put("first", "Ada"); data.put("last", "Lovelace"); data.put("born", 1815); //asynchronously write data ApiFuture<WriteResult> result = docRef.set(data); // ... // result.get() blocks on response System.out.println("Update time : " + result.get().getUpdateTime()); // [END fs_add_data_1] break; } case "aturing": { // [START fs_add_data_2] DocumentReference docRef = db.collection("users").document("aturing"); // Add document data with an additional field ("middle") Map<String, Object> data = new HashMap<>(); data.put("first", "Alan"); data.put("middle", "Mathison"); data.put("last", "Turing"); data.put("born", 1912); ApiFuture<WriteResult> result = docRef.set(data); System.out.println("Update time : " + result.get().getUpdateTime()); // [END fs_add_data_2] break; } case "cbabbage": { DocumentReference docRef = db.collection("users").document("cbabbage"); Map<String, Object> data = new ImmutableMap.Builder<String, Object>() .put("first", "Charles") .put("last", "Babbage") .put("born", 1791) .build(); ApiFuture<WriteResult> result = docRef.set(data); System.out.println("Update time : " + result.get().getUpdateTime()); break; } default: } } void runAQuery() throws Exception { // [START fs_add_query] // asynchronously query for all users born before 1900 ApiFuture<QuerySnapshot> query = db.collection("users").whereLessThan("born", 1900).get(); // ... // query.get() blocks on response QuerySnapshot querySnapshot = query.get(); List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments(); for (QueryDocumentSnapshot document : documents) { System.out.println("User: " + document.getId()); System.out.println("First: " + document.getString("first")); if (document.contains("middle")) { System.out.println("Middle: " + document.getString("middle")); } System.out.println("Last: " + document.getString("last")); System.out.println("Born: " + document.getLong("born")); } // [END fs_add_query] } void retrieveAllDocuments() throws Exception { // [START fs_get_all] // asynchronously retrieve all users ApiFuture<QuerySnapshot> query = db.collection("users").get(); // ... // query.get() blocks on response QuerySnapshot querySnapshot = query.get(); List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments(); for (QueryDocumentSnapshot document : documents) { System.out.println("User: " + document.getId()); System.out.println("First: " + document.getString("first")); if (document.contains("middle")) { System.out.println("Middle: " + document.getString("middle")); } System.out.println("Last: " + document.getString("last")); System.out.println("Born: " + document.getLong("born")); } // [END fs_get_all] } void run() throws Exception { String[] docNames = {"alovelace", "aturing", "cbabbage"}; // Adding document 1 System.out.println("########## Adding document 1 ##########"); addDocument(docNames[0]); // Adding document 2 System.out.println("########## Adding document 2 ##########"); addDocument(docNames[1]); // Adding document 3 System.out.println("########## Adding document 3 ##########"); addDocument(docNames[2]); // retrieve all users born before 1900 System.out.println("########## users born before 1900 ##########"); runAQuery(); // retrieve all users System.out.println("########## All users ##########"); retrieveAllDocuments(); System.out.println("###################################"); } /** * A quick start application to get started with Firestore. * * @param args firestore-project-id (optional) */ public static void main(String[] args) throws Exception { FileInputStream serviceAccount; try { serviceAccount = new FileInputStream("nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn.json"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .setDatabaseUrl("llllllllllllllllllllllll") .build(); FirebaseApp.initializeApp(options); System.out.println("あいうえお"); } catch ( Exception e) { e.printStackTrace(); } // default project is will be used if project-id argument is not available // String projectId = (args.length == 0) ? null : args[0]; String projectId = "aaaaaa" ; Quickstart quickStart = (projectId != null) ? new Quickstart(projectId) : new Quickstart(); quickStart.run(); } }

エラーコード(コンソール)

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. あいうえお 情報: Failed to detect whether we are running on Google Compute Engine. [火 5月 19 19:04:55 JST 2020] Exception in thread "main" java.lang.NullPointerException at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:888) at com.google.cloud.ServiceOptions$Builder.setCredentials(ServiceOptions.java:210) at com.google.cloud.firestore.FirestoreOptions$Builder.build(FirestoreOptions.java:223) at firebase.sample.Quickstart.<init>(Quickstart.java:64) at firebase.sample.Quickstart.main(Quickstart.java:222)

やりたいこととして、firestoreにデータをアップデートならびに取得したいと考えています。
よろしくお願いいたします。

参照ページ
https://github.com/GoogleCloudPlatform/java-docs-samples/blob/bf241de610e708dd2bc9b291462191c00a0c88ec/firestore/src/main/java/com/example/firestore/Quickstart.java#L91-L100

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2020/05/19 18:49

これはどこでどうやって動かしましたか?
YT0014

2020/05/20 07:55

nnn...n.json も、ご提示ください。 このファイルを正確に作成していないと、正常に動かないと思います。
guest

回答1

0

自己解決

自己解決いたしました。
大変失礼いたしました。

投稿2020/06/08 12:13

kuroishi

総合スコア53

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問