Retrieve Real-Time Data In Firebase Using Android Studio - Part Two

Introduction

 
This article demonstrates how to Retrieve Real-Time Data in Firebase using Android Studio. Also, you will see how to get the data from a Firebase real-time database. In this part, I will complete the remaining process of retrieving real-time data using Firebase.
 
Refer to part one from the following link.

Real-Time Database

 
Firebase provides a real-time database and back-end as a service. The service provides application developers an API that allows application data to be synchronized across clients and stored on Firebase's cloud. The company provides client libraries that enable integration with Android, iOS, JavaScript, Java, Objective-C, swift and Node.js applications. The database is also accessible through a REST API and bindings for several JavaScript frameworks such as AngularJS, React, Ember.js and Backbone.js. The REST API uses the Server-Sent Events protocol, which is an API for creating HTTP connections for receiving push notifications from a server.
 
Prerequisites
  • Android Studio
  • Before using Firebase Real-time Database, make sure that you have connected your Android app to Firebase.
  • Android Emulator
The steps given below are required to be followed in order to create a retrieve data in Android, using Android Studio.
 
Step 1
 
Next, go to Gradle Scripts >> build.gradle (Module: app). Select build.gradle. The app gradle compiles the code, and then the build types will appear. Just replace that with the following code and add the Firebase Core and Firebase Database Gradle to your project, or you can also use Gradle.
 
Dependencies Class
  1. dependencies {  
  2.        classpath 'com.android.tools.build:gradle:3.1.1'  
  3.        classpath 'com.google.gms:google-services:3.2.0'  }
Gradle for app
  1. dependencies {  
  2.     implementation fileTree(dir: 'libs', include: ['*.jar'])  
  3.     implementation 'com.android.support:appcompat-v7:26.1.0'  
  4.     implementation 'com.android.support.constraint:constraint-layout:1.0.2'  
  5.     testImplementation 'junit:junit:4.12'  
  6.     androidTestImplementation 'com.android.support.test:runner:1.0.1'  
  7.     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'  
  8.     implementation 'com.google.firebase:firebase-core:15.0.0'  
  9.     implementation 'com.google.firebase:firebase-database:15.0.0'  
  10.     implementation 'com.firebase:firebase-client-android:2.4.0'  
  11. }  
  12. apply plugin: 'com.google.gms.google-services'  
Step 2
 
Go to Console Firebase > Click OverView > Database > Real-Time DB. Select the Real-Time DB to create three new Name and Value, just copy the Database table link for Firebase DB.
 
 
 
Step 3
 
Next, go to app >> res >> layout >> activity_main.xml. Select the files to follow the code as given below.
  1. <?xmlversionxmlversion="1.0"encoding="utf-8"?>  
  2. <RelativeLayoutxmlns:androidRelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"  
  3.    xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.    xmlns:tools="http://schemas.android.com/tools"  
  5.    android:layout_width="match_parent"  
  6.    android:layout_height="match_parent"  
  7.    tools:context=".MainActivity">  
  8.   
  9. <Buttonandroid:idButtonandroid:id="@+id/button"  
  10.    android:layout_width="wrap_content"  
  11.    android:layout_height="wrap_content"  
  12.    android:layout_alignParentTop="true"  
  13.    android:layout_centerHorizontal="true"  
  14.    android:layout_marginTop="155dp"  
  15.    android:text="Button"/>  
  16.   
  17. </RelativeLayout>  
Step 4
 
Next, go to app >> src >> java >> Domain Name >> MainActivity.java . Select MainActivity file to follow the code as given below.
  1. package io.github.saravanan_selvaraju.myapplication;   
  2.    
  3. import android.support.annotation.MenuRes;    
  4. import android.support.v7.app.AppCompatActivity;    
  5. import android.os.Bundle;    
  6. import android.util.Log;    
  7. import android.widget.Button;    
  8. import android.widget.TextView;    
  9. import com.firebase.client.DataSnapshot;    
  10. import com.firebase.client.Firebase;    
  11. import com.firebase.client.FirebaseError;    
  12. import com.firebase.client.ValueEventListener;    
  13. import java.util.Map;    
  14.   
  15. publicclass MainActivity extends AppCompatActivity   
  16. {    
  17.    private Firebase mRef;    
  18.    private Button mbutton;   
  19.    
  20.    @Overrideprotectedvoid   
  21.    onCreate(Bundle savedInstanceState)   
  22.    {    
  23.       super.onCreate(savedInstanceState);            
  24.       setContentView(R.layout.activity_main);            
  25.       mRef = new Firebase("https://retrieve-f165f.firebaseio.com");  // DataBase Profile Link            
  26.       mbutton = (Button) findViewById(R.id.button);            
  27.       mbutton.setOnClickListener(new android.view.View.OnClickListener()   
  28.       {    
  29.          @Overridepublicvoid onClick(android.view.View view)   
  30.             {                  mRef.addValueEventListener(new ValueEventListener()   
  31.          {    
  32.          @Overridepublicvoid onDataChange(DataSnapshot dataSnapshot)   
  33.             {                  Map<String, String>map = dataSnapshot.getValue(Map.class);                            
  34.                String name = map.get("Name");                            
  35.                String age = map.get("Age");                            
  36.                String state = map.get("State");                            
  37.                Log.v("E_VALUE","Name:" + name);                            
  38.                Log.v("E_VALUE","Age:" + age);                            
  39.                Log.v("E_VALUE","State:" + state);                        
  40. }  @Overridepublicvoid onCancelled(FirebaseError firebaseError)   
  41. {   }                    
  42. });}});  }  }    
"mRef = new Firebase("....LINK.... ");".
 
This is your firebase DB link, It is used to help the database table connect to your app
 
Next, go to Android Studio and deploy the application. Select Emulator or your Android Device with USB debugging enabled. Give it a few seconds to make installations and set permissions.
 
FIRST OUTPUT  
 
When you click on a button, that data will be displayed in the given Logcat.
 
 
 
 
 
Step 5
 
Next, go to app >> res >> layout >> activity_main.xml. Select the files to follow the code as given below.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context=".MainActivity">  
  8.   
  9.     <ListView  
  10.         android:id="@+id/ListView"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="match_parent"  
  13.         android:layout_alignParentTop="true" />  
  14.   
  15. </RelativeLayout>  
Preview
 
 
 
Step 6
 
Again, go to app >> src >> java >> Domain Name >> MainActivity.java . Select MainActivity file to follow the code as given below.
  1. package io.github.saravanan_selvaraju.myapplication;  
  2.   
  3. import android.support.v7.app.AppCompatActivity;  
  4. import android.os.Bundle;  
  5. import android.widget.ArrayAdapter;  
  6. import android.widget.ListView;  
  7. import com.firebase.client.ChildEventListener;  
  8. import com.firebase.client.DataSnapshot;  
  9. import com.firebase.client.Firebase;  
  10. import com.firebase.client.FirebaseError;  
  11. import java.util.ArrayList;  
  12.   
  13. public class MainActivity extends AppCompatActivity {  
  14.   
  15.     private Firebase mRef;  
  16.     private ArrayList<String> mUsername = new ArrayList<>();  
  17.     private ListView mListView;  
  18.   
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.   
  24.         mRef = new Firebase("https://retrieve-f165f.firebaseio.com");  // DataBase Profile Link  
  25.         mListView = (ListView) findViewById(R.id.ListView);  
  26.         final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mUsername);  
  27.         mListView.setAdapter(arrayAdapter);  
  28.         mRef.addChildEventListener(new ChildEventListener() {  
  29.             @Override  
  30.             public void onChildAdded(DataSnapshot dataSnapshot, String s) {  
  31.                 String value = dataSnapshot.getValue(String.class);  
  32.                 mUsername.add(value);  
  33.                 arrayAdapter.notifyDataSetChanged();  
  34.             }  
  35.   
  36.             @Override  
  37.             public void onChildChanged(DataSnapshot dataSnapshot, String s) {  
  38.             }  
  39.             @Override  
  40.             public void onChildRemoved(DataSnapshot dataSnapshot) {  
  41.             }  
  42.             @Override  
  43.             public void onChildMoved(DataSnapshot dataSnapshot, String s) {  
  44.             }  
  45.             @Override  
  46.             public void onCancelled(FirebaseError firebaseError) {  
  47.             }  
  48.         });  
  49. }  
  50. }   
Step 7
 
Next, go to Android Studio and deploy the application. Select Emulator or your Android Device with USB debugging enabled. Give it a few seconds to make installations and set permissions.
 
OUTPUT 
 
Real-Time data will be displayed in the given ListView.
 
 
 

Summary

 
Now, you have successfully retrieved Real-Time Data in an Android application using Andriod Studio and Java.


Similar Articles