Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Getting Started With Cloud Firestore - Part One

DZone's Guide to

Getting Started With Cloud Firestore - Part One

Learn how to get started and write your first data with Cloud Firestore, a scalable database for mobile, web, and server development from Firebase.

· Mobile Zone
Free Resource

In my book The Definitive Guide to Firebase, I was all-in on chapters before the release of Cloud Firestore, so, instead of delaying the book to get a Firestore chapter in, I promised I'd write a series of blog posts introducing you to Firestore and how you can get started with using it on Android.

Cloud Firestore is designed to be a flexible, scalable database for mobile, web and server development. It shares some similarities with the Firebase Realtime Database - notably keeping your data in sync across apps using realtime listeners, as well as having offline support. It's designed to let you build responsive apps that work regardless of connectivity, and which continue to give a good app experience through times of network latency. As with the rest of Firebase, it also offers integration across other Firebase and Google Cloud Platform products, including support for Cloud Functions triggers.

At the time of writing this post, Cloud Firestore is in beta release, so some details may change.

Getting Started

Step 1. Create an App and Connect to Firebase

When creating apps that use Firebase, you need to create a Firebase project on the Firebase console and a client app on Android, iOS or the Web that connects to that project. The project handles everything cloud-side that your app will use. In this section, you'll create a client app using Android studio, and with the tools inside Android Studio, you'll create the Firebase (cloud-side) project and connect the two.

Get started by creating an app using Android Studio that uses the empty activity template.

Then, using Android Studio, open the Firebase Assistant by selecting the Tools menu, and then picking Firebase. You'll notice that the assistant window will open on the right-hand side of the screen.

There's no support for Cloud Firestore in the assistant at present, but you can still use it to get started. Pick Analytics, and open the node. You can see this here:

Select 'Log an Analytics event' and you'll see two buttons: 'Connect to Firebase' and 'Add Analytics to your app.'

Select the first button 'Connect to Firebase', and you'll see a dialog listing your existing Firebase projects, or the ability to create a new one. In this case, I said to create a new project called 'FirebaseBlog', and hit 'Connect to Firebase.'

Remember the name you used for the project. In my case (above) you can see I used 'FirestoreBlog.' Once this is done, you'll see that the assistant updates with the first button as completed, and the second 'Add analytics to your app' is now available to press.

Go ahead and press it, and you'll see this dialog:

Go ahead and press 'Accept Changes'. This will download and install the required Google-Services.json file that Firebase requires to connect your app to your project, as well as adding the required configuration files for Firebase.

You don't yet have Firestore configured, so you'll do that next.

Step 2. Connect Your App to Firestore

In the previous section, you created an app using Android Studio and connected it to a Firebase project that was created from within the Firebase Assistant. In this step, you'll configure the Firebase console (cloud-side) project to use Cloud Firestore, and you'll then configure the Android application to use the Cloud Firestore libraries.

Go to https://console.firebase.google.com, and find the project that you created earlier.

Once you open it, look at the navigation on the left-hand side, and find 'Database.'

Select Database, and you'll be given the option to use Cloud Firestore or the Realtime Database. Choose 'Try Firestore Beta' to use Cloud Firestore.

You'll be asked for which mode you want to start Firestore in - Locked, which requires users to be logged in and given permissions to access your database, and Test, which allows anyone to read/write your data.

You should always use locked mode in real apps. It's ok to start in test mode for development, but don't forget to set up security rules before you go public!

Click 'Enable.'

When you're done you'll see something like this - an empty collection denoting you don't have any data yet. Don't worry, you'll soon have some.

The last step is to add the Firestore APIs to your client app by updating the build.gradle file in Android Studio.

To to this, open Android Studio, and make sure that the Project Navigator at the top left of the screen has 'Project' selected. Then open the 'app' folder, and find build.gradle.

Within the dependencies section of build.gradle, add the following line:

compile 'com.google.firebase:firebase-firestore:11.4.2'

Note that there is also a line with the details of firebase-code like this:

implementation 'com.google.firebase:firebase-core:11.4.2'

You should make sure that the version number of this matches the Firestore version that you just pasted in (i.e. 11.4.2 or whatever the latest version is when you are doing it)

You'll get a message to sync your project. It should complete without error. If you have any errors, please post them in the chat below!

Step 3. Write Your First Data

We'll write a simple piece of data to validate that everything is connected properly. In the next post in this series, you'll take this a bit further, examining typical CRUD operations in Firestore, but for now, let's just do a write.

Update your MainActivity.java file to the following:

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        Map<String, Object> user = new HashMap<>();
        user.put("name", "Laurence Moroney");
        user.put("email", "test@laurencemoroney.com");
        db.collection("users")
                .add(user)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Log.d("FirestoreDemo", "DocumentSnapshot added with ID: " + documentReference.getId());
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w("FirestoreDemo", "Error adding document", e);
                    }
                });
    }
}

This, upon running the app, will create a new document with the contents of the HashMap and add it to the collection called 'users.' You can run this in the emulator in Android Studio. Upon a successful run, go back to your Firebase Console, and you should see something like this:

If you've gotten this far, well done! You've now built an app that's connected to Cloud Firestore. In the next post in this series, we'll look into more detail on managing your data - reading, writing, querying, and more!

Topics:
mobile ,firebase ,cloud firestore ,android ,mobile app development

Published at DZone with permission of Laurence Moroney, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}