Android Firebase Real Time Insert EditText Data Into Database Tutorial

How to configure Firebase project first time and send multiple data into Firebase real time database from android application.

Firebase is a famous product from Google. It comes with many different facilities like Firebase Analytics, Firebase Real Time database, Firebase Cloud messaging, Firebase Storage, Firebase Static website hosting etc. So in this tutorial we would going to learn about Firebase real time database insertion technique.

What we are doing in this project : In this example we would create a application with Two EditText and one button. Now when application user clicks on Insert button then the data will automatically insert into Firebase real time database using node storage technique. Means each inserted data has stored into a separate node with unique ID.

Contents in this project Android Firebase Real Time Insert EditText Data Into Database Tutorial :

1. Open firebase.google.com .

2. Click on SIGN IN .

3. Now Log-In with your Gmail Account.

4. After successfully Login click on GO TO CONSOLE .

5. Click on Add Project.

6. Now Add Project name and select your country then click on CREATE PROJECT .

7. Click on Add Firebase To Your Android App .

8. Now add your Android Studio Application package name, App app nick name and enter SHA 1 certificate. To get SHA-1 certificate from Android studio read my this tutorial. This would help you a lot.

9. Click on REGISTER APP button.

10. Now download google-services.json file into your computer.

11. The google-services.json file contains all the important information regarding to your app project. Now we need to put this google-services.json file into our application folder. For example my this project name is FirebaseInsertData-Android-Examples.com then open your project folder and goto -> app . Now paste the downloaded google-services.json file here like i did in below screenshot.

12. Now click on Database -> Rules .

13. Add below rules in Rules section.

{
 "rules": {
 ".read": true,
 ".write": true
 }
}

14. Now open your Project’s build.gradle(Project) file.

15. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

16. Open your project’s build.gradle(Module:app) file.

17. Add compile ‘com.firebase:firebase-client-android:2.4.0’ and compile ‘com.google.firebase:firebase-database:10.0.1’ inside dependencies block .

18. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

19. Now add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

 20. Screenshot after adding all above code :

21. Add Internet permission inside AndroidManifest.xml file.

 

<uses-permission android:name="android.permission.INTERNET" />

 

Source code starts from here :

1. Add Two EditText and one button in activity_main.xml file.

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/name"
    android:hint="Enter Student Name"
    android:gravity="center"
    android:layout_marginTop="40dp"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/phone_number"
    android:hint="Enter Student Phone Number"
    android:gravity="center"
    android:layout_below="@+id/name"
    android:layout_marginTop="10dp"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/submit"
    android:layout_below="@id/phone_number"
    android:text="Insert Data Into Firebase Database"
    android:layout_marginTop="10dp"/>

2. Create a JAVA class named as StudentDetails.java .

package com.android_examples.firebaseinsertdata_android_examplescom;

/**
 * Created by Juned on 7/25/2017.
 */

public class StudentDetails {


    private String name;
    private String phoneNumber;

    public StudentDetails() {
        // This is default constructor.
    }

    public String getStudentName() {

        return name;
    }

    public void setStudentName(String name) {

        this.name = name;
    }

    public String getStudentPhoneNumber() {

        return phoneNumber;
    }

    public void setStudentPhoneNumber(String phonenumber) {

        this.phoneNumber = phonenumber;
    }

}

2. Create Button object, EditText objects, 2 String variables to hold EditText values, Static Firebase_Server_URL, Firebase object, DatabaseReference object and Database_Path in MainActivity.java file.

Button SubmitButton ;

EditText NameEditText, PhoneNumberEditText;

// Declaring String variable ( In which we are storing firebase server URL ).
public static final String Firebase_Server_URL = "https://insertdata-android-examples.firebaseio.com/";

// Declaring String variables to store name & phone number get from EditText.
String NameHolder, NumberHolder;

Firebase firebase;

DatabaseReference databaseReference;

// Root Database Name for Firebase Database.
public static final String Database_Path = "Student_Details_Database";

3. Set activity context to firebase object and then assign Firebase_Server_URL to firebase object. Now assign Database path to DatabaseReference object.

Firebase.setAndroidContext(MainActivity.this);

firebase = new Firebase(Firebase_Server_URL);

databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

4. Assign ID’s to EditText and button.

SubmitButton = (Button)findViewById(R.id.submit);

NameEditText = (EditText)findViewById(R.id.name);

PhoneNumberEditText = (EditText)findViewById(R.id.phone_number);

5. Create GetDataFromEditText method.

public void GetDataFromEditText(){

    NameHolder = NameEditText.getText().toString().trim();

    NumberHolder = PhoneNumberEditText.getText().toString().trim();

}

6. Add Click Listener on Button and type the below code inside button click method. I have explained each line work by commenting upon it.

SubmitButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        StudentDetails studentDetails = new StudentDetails();

        GetDataFromEditText();

        // Adding name into class function object.
        studentDetails.setStudentName(NameHolder);

        // Adding phone number into class function object.
        studentDetails.setStudentPhoneNumber(NumberHolder);

        // Getting the ID from firebase database.
        String StudentRecordIDFromServer = databaseReference.push().getKey();

        // Adding the both name and number values using student details class object using ID.
        databaseReference.child(StudentRecordIDFromServer).setValue(studentDetails);

        // Showing Toast message after successfully data submit.
        Toast.makeText(MainActivity.this,"Data Inserted Successfully into Firebase Database", Toast.LENGTH_LONG).show();

    }
});

Complete source code :

Code for MainActivity.java file.

package com.android_examples.firebaseinsertdata_android_examplescom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class MainActivity extends AppCompatActivity {

    Button SubmitButton ;

    EditText NameEditText, PhoneNumberEditText;

    // Declaring String variable ( In which we are storing firebase server URL ).
    public static final String Firebase_Server_URL = "https://insertdata-android-examples.firebaseio.com/";

    // Declaring String variables to store name & phone number get from EditText.
    String NameHolder, NumberHolder;

    Firebase firebase;

    DatabaseReference databaseReference;

    // Root Database Name for Firebase Database.
    public static final String Database_Path = "Student_Details_Database";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Firebase.setAndroidContext(MainActivity.this);

        firebase = new Firebase(Firebase_Server_URL);

        databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

        SubmitButton = (Button)findViewById(R.id.submit);

        NameEditText = (EditText)findViewById(R.id.name);

        PhoneNumberEditText = (EditText)findViewById(R.id.phone_number);

        SubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                StudentDetails studentDetails = new StudentDetails();

                GetDataFromEditText();

                // Adding name into class function object.
                studentDetails.setStudentName(NameHolder);

                // Adding phone number into class function object.
                studentDetails.setStudentPhoneNumber(NumberHolder);

                // Getting the ID from firebase database.
                String StudentRecordIDFromServer = databaseReference.push().getKey();

                // Adding the both name and number values using student details class object using ID.
                databaseReference.child(StudentRecordIDFromServer).setValue(studentDetails);

                // Showing Toast message after successfully data submit.
                Toast.makeText(MainActivity.this,"Data Inserted Successfully into Firebase Database", Toast.LENGTH_LONG).show();

            }
        });

    }

    public void GetDataFromEditText(){

        NameHolder = NameEditText.getText().toString().trim();

        NumberHolder = PhoneNumberEditText.getText().toString().trim();

    }
}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.android_examples.firebaseinsertdata_android_examplescom.MainActivity"
    android:layout_margin="10dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Firebase Insert Into Database"
        android:textSize="20dp"
        android:textAlignment="center"
        android:textColor="#000"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:hint="Enter Student Name"
        android:gravity="center"
        android:layout_marginTop="40dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/phone_number"
        android:hint="Enter Student Phone Number"
        android:gravity="center"
        android:layout_below="@+id/name"
        android:layout_marginTop="10dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/submit"
        android:layout_below="@id/phone_number"
        android:text="Insert Data Into Firebase Database"
        android:layout_marginTop="10dp"/>

</RelativeLayout>

Code for StudentDetails.java file.

package com.android_examples.firebaseinsertdata_android_examplescom;

/**
 * Created by Juned on 7/25/2017.
 */

public class StudentDetails {


    private String name;
    private String phoneNumber;

    public StudentDetails() {
        // This is default constructor.
    }

    public String getStudentName() {

        return name;
    }

    public void setStudentName(String name) {

        this.name = name;
    }

    public String getStudentPhoneNumber() {

        return phoneNumber;
    }

    public void setStudentPhoneNumber(String phonenumber) {

        this.phoneNumber = phonenumber;
    }

}

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android_examples.firebaseinsertdata_android_examplescom">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots :

Firebase Real Time

Download Code