Easy to use Cloud Firestore (Android)

Introduction

Note the basic usage of CloudFirestore on Android. (Simple data transmission / reception from installation, etc.) The language used is Java, and the development environment is Android Studio. Please note that this is the first post, so I think there are many points that are difficult to see.

About Firestore

Firestore is a NoSQL database. The file structure is as shown in the image. There is a document in the collection and the data in it is used. You can also create subcollections within your document. structure-data.png

Creating and preparing a project

Click Create Project from the Firebase home page and click Add Project. Set your favorite name, Analytics is enabled, select an account and select a project. Created. Since the application is Android this time, select Android.

Add Firebase to your Android app

** Step 1 App registration ** You can enter only the Android package here. Enter your nickname and SHA-1 if necessary. (No input this time) ** Step 2 Download the configuration file ** Download google-services.json Switch the display method on the upper left to Project and introduce the json file in the app OK if the json file exists in the same location as the image on the right of the site ** Step 3 Add Firebase SDK ** Added what is written on the site to the build gradle. In addition to the content described on the site, the following content has been added to the app level gradle.

app


dependencies {
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-firestore:20.0.0'
}

The version is described by checking the latest available library from the lower this site.

** Step 4 Run the app and check the installation ** You can skip here as it may not end. Confirmation is complete if you run the app and logcat shows *** I / FirebaseInitProvider: FirebaseApp initialization successful ***. ** Step 5 Create firestore ** Click Cloud Firestore on the left tab of the site to create a database For the rule, select the production environment mode this time. (Test mode will be denied access unless updated for 30 days) Choose a suitable location. Because the rules are strict if it is left as it is Change *** write: if false to write: if true *** 53c13ab8b30c6ebcc4556a9541a4f954.png The preparation is complete.

code

Write a little code that can be used for sending / receiving and others. Try running it while checking the Firestore.

Specifying documents and collections

It can be specified in the following statement. If the specified document / collection does not exist, it will be created when the data is saved.

DocumentReference mDocRef = FirebaseFirestore.getInstance().document("Collection name/Document name");

Send

First of all, I will introduce the code of the transmission process.

Save Map

Map<String, Object> data = new HashMap<>();
       data.put("A","Apple");
       data.put("B","Mandarin orange");
       data.put("C","Grape");
        mDocRef.set(data);

Save list

ArrayList<String> group = new ArrayList<>();
        group.add("Apple");
        group.add("Mandarin orange");
        group.add("Grape");
        Map<String, Object> data = new HashMap<>();
        data.put("Field name",group);
        mDocRef.set(data);

Receive

Next, I will introduce the code to get the value of Firebase

Get Map

mDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                       //Processing when the value can be obtained
                        String save = (String) document.get("Field name");//
                    } else {
                        //What to do when the value does not exist
                } else {
                    //Processing when acquisition fails
                }

            }
        });

Get list

mDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                       //Processing when the value can be obtained
                       ArrayList<String> group =  (ArrayList<String>) document.get("Field name");
                    } else {
                       //What to do when the value does not exist
                    }
                } else {
                    //Processing when acquisition of value fails
                }

            }
        });

Other code that you might use often

Next, write the code that you might use.

Processing when saving succeeds or fails

Described after the process of sending data.

mDocRef.set(data).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    ///Processing when saving is successful
                } else {
                    ///Processing when saving fails
                }
            }
        });

What to do when the value changes

Executed at startup and when the value changes

mDocRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
                    @Override
                    public void onEvent(@Nullable DocumentSnapshot snapshot,
                                        @Nullable FirebaseFirestoreException e) {

                        if (snapshot != null && snapshot.exists()) {
                            Log.d("TAG", "Current data: " + snapshot.getData());
                            //What to do when it changes
                        }
                    }
        });

at the end

This is the end of the introduction of how to use Firestore. Thank you very much.

Recommended Posts

Easy to use Cloud Firestore (Android)
Easy to use array.map (&: method)
Function is very easy to use
[Swift] How to install Firebase ~ How to use Realtime Database & Cloud Firestore
Use ViewModel to rotate Android apps roughly
How to use ExpandableListView in Android Studio
Super easy way to use enum with JSP
How to use Alibaba Cloud LOG Java Producer
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
Introduction to Android Layout
How to use Twitter4J
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
How to use Truth (assertion library for Java / Android)
How to use identity
[Android Studio] I want to use Maven library on Android
How to use hashes
[Note] Challenge to develop Android application for business use
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
Easy to maintain FizzBuzz
How to use OpenCV 4 on Android and view camera live view
Use Java included with Android Studio to build React Native
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
Easy to create Processing library
Use serial communication on Android
How to use java Optional
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
How to use java class
How to use Swift UIScrollView
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use rails join
[java] Reasons to use static
Rbenv command to use Ruby
Ruby: How to use cookies
How to use dependent :: destroy
Use native code on Android
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation