Firebase: Real-time database setup and configuration
In our previous section, we learned about the Firebase Real-time database, its key capabilities, and alternatives. Now, we will discuss how we set up and configure an Android application with Firebase to use the Real-time database in Firebase. The starting step will be the same, but in this section, we will use Kotlin rather than Java. So let's start with the starting steps and elaborate on each step, which is performed to set up and configure the application to use a Real-time database in Firebase.
In the first step, we will create a new Android Studio project with an empty activity and Kotlin language and give it name FirebaseRealtimeDatabaseExample.
In the next step, we will connect our Android Application with the Firebase either from Firebase Assistant or manually using console. After that, we will add all the required libraries and plugin to our app.gradle file. And we will also add mavenLocal() as our repository and all projects.
In the next step, we will go to the Firebase console and look at the Real-time database. In Developers-> Database, there will be two options, i.e., cloud Firestore and Real-time database.
In the next step, we will create a database by clicking on the Create database. After clicking on Create database, a popup box is open where we actually create a database with specific rules. We will talk about these rules later in this section. But for now, we will select start in test mode where anybody can access our data, and later we change these rules. And last we select on Enable.
After clicking on Enable, the real-time database will be enabled with a database by default. Here, we have Data, Rules, Backups, and, Usage for data storing, security rules, backups, and usage, respectively.
Before understanding the next steps, we will talk about the Firebase Database Rules.
The Real-time database provides a declarative rules language. It defines how our data should be structured, how it should be indexed, and when our data can be read from and written to. By default, read and write access to our database is restricted, so only authenticated users can read or write data.
To get started without setting up Authentication, we can configure our rules for public access. These rules make our database open to anyone, even people not using our app, read and write access to our database.
If we want to allow authenticated users for accessing read and write to our database, then we will use the following rules:
This will make sure that user only who have been authenticated using firebase can read and write to our database.
In the next step, we will go to the console and go to database rules and modify these rules to authenticated users.
After performing the required changes in the rules, we will publish them.
Now, our database is set with specific rules, and we can use it now. In the next section, we will learn how we perform read and write operations in a Real-time database.