Build a PhoneBook with Cloud FireStore in 10 minutes
Tags: firebase, firestore, beginners, android
Published: 2017-10-19 07:22:48

---
title: Build a PhoneBook with Cloud FireStore in 10 minutes
published: true
description: Build a PhoneBook with Cloud FireStore in 10 minutes
tags: Firebase, Firestore, beginners, android
---
![Alt text image](https://thepracticaldev.s3.amazonaws.com/i/5syh6d4lvg8bnbty6pwe.jpg)
According to the Documentation, Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.
Like Firebase Realtime Database it keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity, this is just amazing if you ask me, it solves the whole essence of PWA’s. You may ask how, well
Cloud Firestore caches data that your app is actively using, so the app can write, read, listen to, and query data even if the device is offline. When the device comes back online, Cloud Firestore synchronizes any local changes back to Cloud Firestore.
Cloud Firestore also offers seamless integration with other Firebase and Google Cloud Platform products, including Cloud Functions.
However, Cloud Firestore is still in beta release but if you’re enthusiastic (like me) and want to get hands on immediately, then this tutorial will help you get started with basic read, write, update and delete operations.
**What you’ll learn**
If you don’t know these yet then, you’ll
Â· Gain a better understanding of Firebase and Firestore
Â· Learn how to add firebase to your project
Â· Learn the FireStore database model and structure
Â· Learn how to write to Cloud FireStore
Â· Learn how to read from Cloud FireStore
Â· Learn how to update an existing data in Cloud FireStore
Â· Learn how to delete data from Cloud FireStore
Â· Learn how to listen for changes in realtime
Â· Learn how to combine all these features to create a Phonebook
As usual I like to prepare my tutorials to be very relative and not so abstract, so i won’t be talking too much, let’s start building something with FireStore.
Create a new android studio project and connect it to firebase. Once again there are two ways you can do this depending on the version of Android studio you’re on. If you’re using the latest version of Android Studio (version 2.2 or later), i recommend using the Firebase Assistant to connect your app to Firebase. The Firebase Assistant can connect your existing project or create a new one for you and automatically install any necessary gradle dependencies. Here’s how you can do it
**To add firebase to your app with Firebase Assistant in Android Studio:**
Â· Click Tools > Firebase to open the Assistant window.
Â· Click to expand one of the listed features (for example, Analytics), then click the provided tutorial link (for example, Log an Analytics event).
Â· Click the **Connect to Firebase** button to connect to Firebase and add the necessary code to your app.
That’s it!
If you are using the earlier versions of Android Studio or you prefer not to use the Firebase Assistant, you can still add Firebase to your app using the Firebase console.
**To manually add Firebase to your app you’ll need a Firebase project and a Firebase configuration file for your app.**
1. Create a Firebase project in the Firebase console, if you don’t already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
2. Click Add Firebase to your Android app and follow the setup steps. If you’re importing an existing Google project, this may happen automatically and you can just download the config file.
3. When prompted, enter your app’s package name. It’s important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
4. At the end, you’ll download a google-services.json file. You can download this file again at any time.
5. If you haven’t done so already, copy this into your project’s module folder, typically app/.
Then you can add any of the Firebase libraries you’d like to use in your project to your build.gradle file, it is good practice to always add com.google.firebase:firebase-core.
This guides are according to the firebase documentary however, if all of this is still not clear to you, you can always find more content on how to setup your firebase project here
Now that you have your firebase project set up, let’s add the dependency for FireStore. As at the time of writing this tutorial, the latest version is compile â€˜com.google.firebase:firebase-firestore:11.4.2’ so add it to your app level build.gradle file dependency block. It might have changed depending on when you’re reading this so always check the Docs for the latest dependency and sync.
Before we proceed let’s take a moment to **understand the FireStore model**
Cloud Firestore is a document database; it stores all your data in documents and collections. Documents operates more like containers of fields(key-value pairs) of diverse data types however a document cannot contain other documents but can point to a sub-collection. Collections on the other hand operate also like documents but in its case, it’s a container of documents hence, it can’t contain anything else but documents.
![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508393686/1_SAND5R-BsO6SH4If0k9P_w_kg0g4f.jpg)

From the above image, “Users is a collection of 3 documents “Joe”, “Tammy and “Vic”. Document Joe however, points to a sub-collection “Workouts which in itself has 3 documents (“Yoga level 2”, “Beginner Jogging”, and “7-minute thighs”). Then document “7-minute thighs further more points to a sub-collection “History which in turn holds 3 more documents etc.
This is deep nesting and it may seem a little bit deep but it is very efficient for query performance in both simple complex query structures. With this idea of how Firestore works, let’s dive into the firebase project we created earlier and start writing some code.
**What are we building?**
For the purposes of understanding the basics of Firestore in the best simple way, we’ll be building a Phone Book database that stores contacts with 3 fields (Name, Email and Phone). We’ll demonstrate how to write, read, update and delete data from the database.
**Let’s get cracking…**
Usually we would have started with setting up EditTextViews in the layout files but we won’t be taking inputs from users yet so we’ll just supply all the data we want to store to the database from our java files….for now. So open up MainActivity and initialize Firestore

{% gist https://gist.github.com/Kennypee/709f5ea7d9ec414710176402909c4b90 %}
You may have noticed I also initialized a Textview object and some String variables there; we’ll use the Textview to read data from the database and the String variables as “keys for storing data into our document.
Considering the model we’ll be working with, it is best to think of the Phonebook we are building as the collection, so let’s add/save a newContact to our PhoneBook.

{% gist https://gist.github.com/Kennypee/cbd2147b190f2fcfb2d96f1d33cc6371 %}
Here we first created a method *addNewContact()*, the method will create the newContact that we’d want to save in the PhoneBook and then pass the fields to it. Next we need to specify in which document we want to save the contact. We do this by extending the Firestore instance we created to accommodate both the collection and the document.
“*db.set (newContact)* this creates the document if it doesn’t already exist and also creates the PhoneBook collection so as to store the data in the appropriate path according to the db path we initialized.
Then we add an OnSuccess/FailureListeners to make a Toast and keep us informed if the contact was registered successfully or if the registration failed.
Looks like we’ve got it all set up, before we run the app, we’ll need to head on over to the firebase console and tweak our RULES Tab a little bit to allow us read and write to the database because at default, nobody can read or write to it. So go to your firebase console, open the project and make sure you select Firestore in the database tab

![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508394906/here_rkv3vf.jpg)

Then open the RULES Tab, by default it looks like this

![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508394980/1_kHGGvMxZjprEjV19bVesow_smxoc7.jpg)

Then add this block of code to override the default security settings and gain external read and write access to your database,

*Match/your-collection/{anything=**}{
allow read, write: if true;
}*

Now your RULES Tab should look like this

![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508395250/1_Rpe2N5iHQVpK9ek4EorSCw_hf1tov.jpg)
This is a terrible idea security wise, if you’re working on a real project or something proprietary, you would definitely want to properly authenticate users and define your security measures clearly. This tweaking is only serving the purpose of this tutorial.
Haven set up the security rules in the console, publish it and wait for a few minutes after which you can now run the app and go back to the DATA Tab on the console. Hurrray!! App works…. You’ve just stored your your data to FireStore.

![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508395399/stored_atazxk.jpg)

Now let’s try and read the data we’ve stored in the database to a TextView.
**READ** | First we create *ReadSingleContact()* method that’ll read the data from the database and pass the data to the TextView object we earlier initialized for this Purpose.
{% gist https://gist.github.com/Kennypee/2dc6dd1f1f60d05048f9e0a6c9c6fa45 %}
If we run the app, it populates the TextView object with the information stored on the database as is expected.

![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508395782/1_N-9rOu_FN4-N0aCrhcHsOQ_rllvxu.jpg)
**UPDATE** | Next we’ll try to update the already stored Contact informations

{% gist https://gist.github.com/Kennypee/8c3db83ea9733af67580985549caec3c %}
Now running the app will update the earlier stored data with the newly provided values in the *UpdateData()* method.
In the DATA Tab on your firebase console, you’ll find that the changes have been updated.
![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508395909/update_r9zq1v.jpg)
And if you run the ReadSingleContact() method again, it’ll update the TextView with the current details.
**REALTIME UPDATE**
Next up, we listen for update on the document “Contacts”, if we update these changes without running the code to Read (fetch) data from the database *(ReadSingleContact())*, we might not be able to see the changes in the UI so we’ll create a method that listens for update in realtime and makes a Toast to notify users of the changes in the database.

{% gist https://gist.github.com/Kennypee/ead8f92bc3697c2b33f6f7a01c1e98b3 %}
**Build the Phonebook app**
Now let’s take input from users instead of just adding and updating the database from the studio. I’ll go ahead and create view objects on the mainActivity layout file to take Inputs for the 3 fields (name, email and phone) such that we can save whatever data the user types into any of these fields to the PhoneBook.
We’ve already done all the major work required so just create the view objects in the layout file and initialize them in the MainActivity.java file. Here’s my activity_main.xml
{% gist https://gist.github.com/Kennypee/dfc3866d62540ec68008483b5e792809 %}
Next we initialize the views in the java file
{% gist https://gist.github.com/Kennypee/a614b7112155657b6bc349eb1249b808 %}
Notice the additions of the view objects as compared to the code gist we had under the WRITE heading. Then to save the details coming from this Views to the database, we’ll just tweak our *newContact.put()* method a little bit to capture its value from the EditTextViews. So we’ll open up the *addNewContact()* method and edit it to capture these changes
{% gist https://gist.github.com/Kennypee/2bd3d4619acb8f9177e42b1bb777b9e3 %}
Then we need to set the save button to call this method, so lets set an onClick listener to the button and call the method in it.
*save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        addNewContact();
    }
});*
Then finally let’s update the TextView with any changes we make to the database in realtime, such that if a user fills up the input fields and clicks the save button, the TextView will update the changes in realtime wether there’s internet Connectivity or not.
{% gist https://gist.github.com/Kennypee/76671765f10159ad386f673f5b52178d %}
And that’s it!! At this point, Users can input their details and save it to the database as well as have that same details read from the database and displayed on their screen.
**DELETE** | Finally lets perform the delete operation to delete the Contact from the database.
![Alt text of image](http://res.cloudinary.com/kennyy/image/upload/v1508396574/deleteData_ffdv4m.jpg)
This method successfully deletes the contact from the PhoneBook database. So congratulations if you followed up to this point, this means you can now perform basic operations on one of the most sophisticated and newest online database in the world. This is just a glimpse of what you can do with Cloud FireStore, there are a lot more features and operations to perform. My intention is just to get you started with the basics.
Thanks for reading, you are welcome to make contributions and ask for clarifications anytime you deem fit. Like always, I’m available (twitter @kenny_io) to provide more clarifications and answer your questions if you have any.
The source code is also available on github if you need it.