📜 ⬆️ ⬇️

Cloud Firestore + Android is easy

Not so long ago, Google released Cloud Firestore. Cloud Firestore is a cloud-based NoSQL database, which Google positions as a replacement for the Realtime Database. In this article I want to tell how to start using it.


Opportunities


Cloud Firestore allows you to store data on a remote server, easily access them and monitor changes in real time. The documentation has an excellent comparison of Cloud Firestore and Realtime Database.


Creation and connection to the project


In the Firebase console, select Database and click on Create database. Next, select the access settings. For review, we will have enough test mode, but on the prode it is better to approach this issue more seriously. You can read more about access modes here .



To configure the project, we perform the following steps:


  1. Add Firebase to the project according to the instructions from here.
  2. Add dependency to app / build.gradle
    implementation 'com.google.firebase:firebase-firestore:18.1.0'

Now everything is ready.


To get acquainted with the basic techniques of working with Cloud Firestore, I wrote a simple application . For it to work, you need to create a project in the Firebase console and add the google-services.json file to the project in Android Studio.


Data storage structure


Firestore uses collections and documents to store data. A document is an entry that contains any fields. Documents are combined into collections. Also, the document may contain nested collections, but on Android it is not supported. If we draw an analogy with the SQL database, the collection is a table, and the document is an entry in this table. One collection can contain documents with a different set of fields.


Receive and write data


In order to receive all the documents of a collection, the following code is sufficient.


 remoteDB.collection(“Tasks”) .get() .addOnSuccessListener { querySnapshot -> //   .   querySnapshot.documents } .addOnFailureListener { exception -> //      } } 

Here we request all documents from the Tasks collection.


The library allows you to create queries with parameters. The following code shows how to get documents from the collection by condition


 remoteDB.collection(“Tasks”) .whereEqualTo("title", "Task1") .get() .addOnSuccessListener { querySnapshot -> //   .   querySnapshot.documents } .addOnFailureListener { exception -> //      } } 

Here we request all documents from the Tasks collection, in which the title field corresponds to the value of Task1 .


Upon receipt of the documents, they can be immediately converted into our data classes.


 remoteDB.collection(“Tasks”) .get() .addOnSuccessListener { querySnapshot -> //   .   querySnapshot.documents val taskList: List<RemoteTask> = querySnapshot.toObjects(RemoteTask::class.java) } .addOnFailureListener { exception -> //      } } 

For recording, you must create a Hashmap with data (where the name of the field acts as a key, and the value of this field as a value) and transfer to the library. The following code demonstrates this.


 val taskData = HashMap<String, Any>() taskData["title"] = task.title taskData["created"] = Timestamp(task.created.time / 1000, 0) remoteDB.collection("Tasks") .add(taskData) .addOnSuccessListener { //   } .addOnFailureListener { //     } 

In this example, a new document will be created and the Firestore will generate an id for it. To set your own id you need to do the following.


 val taskData = HashMap<String, Any>() taskData["title"] = task.title taskData["created"] = Timestamp(task.created.time / 1000, 0) remoteDB.collection("Tasks") .document("New task") .set(taskData) .addOnSuccessListener { //   } .addOnFailureListener { //     } 

In this case, if there is no document with id equal to New task , then it will be created, and if it is, then the specified fields will be updated.


Another option to create / update a document


 remoteDB.collection("Tasks") .document("New task") .set(mapToRemoteTask(task)) .addOnSuccessListener { //   } .addOnFailureListener { //     } 

Subscribe to changes


Firestore allows you to subscribe to data changes. You can subscribe to changes in the collection as well as changes to a specific document


 remoteDB.collection("Tasks") .addSnapshotListener { querySnapshot, error -> // querySnapshot -   // error -  } 

querySnapshot.documents - contains an updated list of all documents
querySnapshot.documentChanges - contains a list of changes. Each object contains a modified document and a type of change. 3 types of changes are possible.
ADDED - document added,
MODIFIED - the document is changed,
REMOVED - Document deleted


Loading large amounts of data


Realtime Database provides a less convenient mechanism for loading large amounts of data, which consists in manually editing a json file and loading it. Firestore out of the box does not provide anything. It was very inconvenient to add new documents until I found a way to download a large amount of information as easily as possible. So that you do not have such problems as mine, I will attach the instructions below on how to quickly and easily load a large amount of data. The instruction was found on the Internet.


  1. Install Node.js and npm
  2. Install the firebase-admin package by running the command
    npm install firebase-admin --save
  3. Generate a json file with collection data. An example can be found in the Tasks.json file .
  4. To download, we need an access key. How to get it is well described in this article.
  5. In the export.js file put down your data
    require ('./ firestore_key.json') - file with access key. I was in the folder with the script
    <YOU_DATABASE> - the name of your firestore database
    "./json/Tasks.json" - the path to the file in which the data lie
    ['created'] - list of field names with type Timestamp
  6. Run script
    node export.js
    The script uses the practices of dalenguyen

Conclusion


I used Cloud Firestore in one of my projects and did not experience any serious problems. One of my collections contains about 15,000 documents and requests for it pass fairly quickly and this is without the use of indexes. Using Cloud Firestore together with Room and Remote Config, you can significantly reduce the number of calls to the database and not go beyond the free limits. At a free rate per day you can read 50,000 documents, write 20,000 and remove 20,000.


Gifka application work


')

Source: https://habr.com/ru/post/447640/


All Articles