Firebase in android studio with example
Table of Contents
Firebase in Android Studio with example:
Connecting Firebase in android studio- In today’s article, I will practically show you how to connect Firebase with Android Studio. I am not using firebase for the first time; Firebase has been my favorite IoT platform for monitoring sensors and for controlling electrical devices. I just love controlling things over long distances using internet as the communication medium. Today, Firebase is among the top IoT platforms, there are so many other IoT platforms like for example blynk application, Ubidots, Thingspeak, Telegram, IFTT, Google Assistant, etc. Each one of these IoT platforms has got it’s own pros and cons. I have used all of these IoT platforms with Arduino, ESP32, and ESP8266.
I have already used Firebase in some intermediate and advanced level projects including,
Firebase Android Application Designing using Android Studio, ESP32 DHT11
Nodemcu RFID Firebase, circuit diagram, and programming
ESP32 Firebase Tutorial, Send Sensor Data to Google Firebase Database
Arduino Firebase Database, Students Attendance system using RFID and GSM
You might be thinking why am I writing this article if I have used Firebase in such intermediate and advanced level projects? Well, today’s article covers the most basic things which include connecting Firebase with the Android Studio. If you don’t know how to design Android applications then you can read my articles on Android Application designing. After reading this article you will be able to connect your Android application with the Firebase using Android studio. Without any further delay, let’s get started!!!
Creating a new Firebase project in Android studio:
First, click on the Android studio icon and it will open up the Android studio
Then click on the New Project button in the Android studio
Then select the empty activity and press the next button
Then provide an application name it doesn’t really matter any name is fine in my case I set the name as FirebaseCrud, and then click on the finish button
After clicking the finish button you will be taken into a window like this
Connect Firebase to Android Studio:
Now once your project successfully launched what you want to do is go to the tools menu click on it, it will show a dropdown menu among all the options click on the firebase.
When you click on the firebase, you will see a new firebase panel will open.
In this panel, you will see a lot of options, but none of them are important to us right now you can see a lot of options like analytics, cloud messaging, authentication, real-time database storage, etc and all that stuff but right now our main focus is on the real-time database. So click on the real-time database, when you clicked on the real-time database it will show you the save and retrieve data link button so you must click on this link as you can see in the below figure
After clicking the save and retrieve data link button, it will show you the save and retrieve data panel in this panel click on connect to firebase as you can see in the below image
When you clicked the connect to firebase button it will a dialog box, simply click build and wait for the sync process
When the build process is finished, press once again the “connect to firebase” button as shown in the below image
After clicking the “connect to firebase” button, you will be taken into a default web browser and you make sure you have logged in into your Google account.
When the firebase database website loaded successfully, simple click on create a project
It will detect your android studio project name automatically so click on the continue button as you can see in the below image
Again click on the continue button
Checked the I accept the google analytics terms and click create project button
So wait for the project creating process it will take a while
After the project creating process simply click the continue button
It will show you a dialog with connect button so click on connect button
After clicking the connect button it will show the message “your android studio project is connected to your firebase Android app”
In the android studio, you will see connected in green color this means that your app is successfully connected
After that click on “add the realtime database SDK to your app” button
When you clicked the button, it will show you a dialog box, simply click on accept changes it will add the dependencies in your app Gradle file
Wait for adding dependencies process it will take time, it depends on the internet connection
When the process is finished, you will see the “dependencies set up correctly” in green color which mean your dependencies are added successfully
When the firebase connecting process is completed, you will see the firebase webpage like this
Firebase Database access Configuration for the Android Studio:
Now we want to configure our access for that you will need to change the default rules by default it is set to false, simply change it to true.
Select Realtime database in the left side panel and click on create the database
then click the next button
Then checked the start in test mode, and click on Enable
Click on the rules tab and from there change the configuration into true now once everything is done click publish
see rules are published
Make sure to use the firebase real-time database version which available on the official firebase website
status so I’m creating a toast here that says firebase connection success so that our connection is successful and it will show the toast now let me test my code let me alone Jim later first might take a while okay now you can see that firebase connection was successful
now I am writing a simple toast message code to test the connection status of our firebase in android studio.
Simple firebase toast message program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.example.firebasecrud; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast.makeText(MainActivity.this, "Firebase Connected Successfully", Toast.LENGTH_LONG).show(); } } |
Simply I create a toast message method here that will show firebase connected successfully message on the screen. Now runs the application to check application is successfully connected with firebase or not, simply click on the run button
As you can see I connected firebase database with android studio successfully
Creating Crud Application using firebase in android studio:
Now I am going to show you how to insert data into firebase in android studio. So I edit the existing project.
I have made a simple application layout as you can see in the below image
Firebase in android studio programming:
activity_main.xml code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:hint="Name" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.412" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.081" /> <EditText android:id="@+id/last_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:hint="Last Name" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.412" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/name" app:layout_constraintVertical_bias="0.094" /> <EditText android:id="@+id/age" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="number" android:hint="Age" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.412" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/last_name" app:layout_constraintVertical_bias="0.127" /> <EditText android:id="@+id/phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="phone" android:hint="Phone number" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.412" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/age" app:layout_constraintVertical_bias="0.171" /> <Button android:id="@+id/btn_insert" android:layout_width="210dp" android:layout_height="54dp" android:text="Insert Data" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.412" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/phone" app:layout_constraintVertical_bias="0.269" /> </androidx.constraintlayout.widget.ConstraintLayout> |
here I created constraintlayout, in this layout I create one insert data button and four editText field name, last name, age, and phone number and I set its attribute as per my requirement. If you want to improve its design so change its attributes. The code is pretty simple so I cannot explain it.
MemberData.java Code:
First, create a new java class named MemberData for getter and setter
Then generate the getter and setter methods simply press the Alt+insert button, it will show a menu in this select the getter and setter methods
After clicking the getter and setter methods, again it will show a dialog box in this dialog box select all fields and press ok button
It will generate the below code automatically
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.example.firebasecrud; public class MemberData { private String Name; private String Last_name; private Integer Age; private Long phone; public MemberData() { } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getLast_name() { return Last_name; } public void setLast_name(String last_name) { Last_name = last_name; } public Integer getAge() { return Age; } public void setAge(Integer age) { Age = age; } public Long getPhone() { return phone; } public void setPhone(Long phone) { this.phone = phone; } } |
MainActivity.java code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.example.firebasecrud; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class MainActivity extends AppCompatActivity { EditText Name,Last_name,Age,Phone; Button InsertData; DatabaseReference ref; MemberData member; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Name=(EditText) findViewById(R.id.name); Last_name=(EditText) findViewById(R.id.last_name); Age=(EditText) findViewById(R.id.age); Phone=(EditText) findViewById(R.id.phone); InsertData=(Button) findViewById(R.id.btn_insert); ref= FirebaseDatabase.getInstance().getReference().child("Member"); member = new MemberData(); InsertData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int M_age=Integer.parseInt(Age.getText().toString().trim()); Long M_phone=Long.parseLong(Phone.getText().toString().trim()); member.setName(Name.getText().toString().trim()); member.setLast_name(Last_name.getText().toString().trim()); member.setAge(M_age); member.setPhone(M_phone); ref.push().setValue(member); Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show(); } }); } } |
Firebase in android studio Program explanation:
1 2 3 4 |
EditText Name,Last_name,Age,Phone; Button InsertData; DatabaseReference ref; MemberData member; |
In the MainActivity class, First, I initialized variable names for the EditText and button. Then I initialized name for DataBaseReference method. Then I initialized the name for MemberData class.
1 2 3 4 5 |
Name=(EditText) findViewById(R.id.name); Last_name=(EditText) findViewById(R.id.last_name); Age=(EditText) findViewById(R.id.age); Phone=(EditText) findViewById(R.id.phone); InsertData=(Button) findViewById(R.id.btn_insert); |
here I can use this to refer to our actual layout that I have created earlier. now you can use a findViewById function to point each variable to our fields.
1 |
ref= FirebaseDatabase.getInstance().getReference().child("Member"); |
Then I created another reference variable to connect to our database
1 |
member = new MemberData(); |
then I call the MemberData class which I have created for getter and setter methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
InsertData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int M_age=Integer.parseInt(Age.getText().toString().trim()); Long M_phone=Long.parseLong(Phone.getText().toString().trim()); member.setName(Name.getText().toString().trim()); member.setLast_name(Last_name.getText().toString().trim()); member.setAge(M_age); member.setPhone(M_phone); ref.push().setValue(member); Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show(); } }); |
then I have created the onclicklistener event. Inside this event, I pass all the variables and their type.
Firebase in android studio final output:
now run the firebase application
Fill the field and press the insert data button, it will show a toast message data inserted as you can in the below image
As you can see all the data is inserted successfully in the firebase database.
Could not parse Error fixing:
When you are getting “could not parse the android application module’s Gradle config. Resolve Gradle build issues and/or resync” error while connecting to firebase in android studio.
For that simply open module-level build Gradle.
Then change the compileSdk version, in my case, my compileSdk version is 32 and I changed it to 31.
And press the sync now button.
With these changes, you will not get this “could not parse the android application module’s Gradle config. Resolve Gradle build issues and/or resync” error message again. So, that’s all for now.