Skip to content Skip to sidebar Skip to footer

Random Matching of Users Firebase and Not Matched Again

Firebase Realtime database is a cloud hosted database that supports multiple platforms Android, iOS and Web. All the data is stored in JSON format and any changes in data, reflects immediately by performing a sync beyond all the platforms & devices. This allows us to build more flexible realtime apps hands with minimal effort.

This article covers nuts integration of firebase realtime database. The other concepts similar performs CRUD operations, data validations, firebase access rules also covered. If yous are new to firebase, I suggest you lot bank check my other articles about Firebase Auth and Firebase Analytics to improve your cognition over firebase.

firebase-realtime-database-android

1. How the Data is Stored – JSON Structured

Firebase realtime database is a schemaless database in which the information is stored in JSON format. Basically the unabridged database is a big JSON tree with multiple nodes. Then when you plan your database, you need to prepare the json construction in style that the information is accessible in easier way by avoiding nesting of child nodes.

Hither is an example of storing list of user profiles and posts in json tree. You tin become through firebase Structure Your Database guide to larn the best practises while defining the database construction.

{   "users": [     {       "name": "Ravi Tamada",       "email": "ravi@androidhive.info",       "accost": "Thirty, XXXX, 1234"     }   ],   "posts": [     {       "id": 100,       "author": "Ravi Tamada",       "content": "This is awesome firebase realtime database...",       "timestamp": "13892733894"     }   ] }        

2. Offline Data

Firebase provides neat support when comes to offline information. It automatically stores the data offline when there is no internet connection. When the device connects to internet, all the data will be pushed to realtime database. All the same enabling disk persistence stores the data offline even though app restarts. Disk persistence can be enabled past calling beneath i line code. Hither is complete guide about firebase offline capabilities.

FirebaseDatabase.getInstance().setPersistenceEnabled(truthful);        

3. Performing CRUD Operations

Before getting into the android app, I would like to give you basic information about performing Crud operations on to realtime database. Later we'll combine all these concepts together to build a simple app with firebase realtime database as backend.

In social club to perform whatever operation on to database whether it tin exist read or write, you need to go the reference to database first. The below lawmaking gives yous reference to database JSON top node. From here you need to use the child node names to traverse farther.

private DatabaseReference mDatabase;  mDatabase = FirebaseDatabase.getInstance().getReference();        

3.1 Inserting Data

To insert data, you lot can use setValue() method on to database reference path. This will create or update the value on path provided. For an example below lawmaking inserts a node called "copyright" in json meridian level.

DatabaseReference mRef = mDatabase.getReference("copyright");  mRef.setValue("©2016 androidhive. All rights Reserved");        

The realtime database accepts multiple information types String, Long, Double, Boolean, Map<String, Object>, List<Object> to store the data. You lot can too use custom java objects to store the information which is very helpful when storing model class straight in database.

Let'south say yous want to shop user profile in the database. Offset you demand to create User model with an empty constructor and other properties.

@IgnoreExtraProperties public form User {      public String name;     public String email;      // Default constructor required for calls to     // DataSnapshot.getValue(User.class)     public User() {     }      public User(Cord proper name, Cord email) {         this.name = proper name;         this.email = e-mail;     } }        

As every user needs a unique Id, yous can generate i past calling push() method which creates an empty node with unique key. So get the reference to 'users' node using child() method. Finally utilise setValue() method to shop the user data.

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");  // Creating new user node, which returns the unique cardinal value // new user node would be /users/$userid/ String userId = mDatabase.push().getKey();  // creating user object User user = new User("Ravi Tamada", "ravi@androidhive.info");  // pushing user to 'users' node using the userId mDatabase.kid(userId).setValue(user);        

By running the above code, a new user node will exist inserted in database with a unique key value. In general, the user id should exist acquired by implementing Firebase Auth in your app which gives you authId that acts as user id.

{   "users": [     "-KTYWvZG4Qn9ZYTc47O6" : {       "e-mail" : "ravi@androidhive.info",       "proper name" : "Ravi Tamada"     },     {       ...     }   ] }        

iii.ii Reading Data

To read the data, you need to attach the ValueEventListener() to the database reference. This event will be triggered whenever there is a change in data in realtime. In onDataChange() you can perform the desired operations onto new data.

Below is the outcome listener that is triggered whenever there is a change in user profile information that we created earlier.

mDatabase.kid(userId).addValueEventListener(new ValueEventListener() {     @Override     public void onDataChange(DataSnapshot dataSnapshot) {          User user = dataSnapshot.getValue(User.course);          Log.d(TAG, "User name: " + user.getName() + ", electronic mail " + user.getEmail());     }      @Override     public void onCancelled(DatabaseError error) {         // Failed to read value         Log.w(TAG, "Failed to read value.", error.toException());     } });        

3.3 Updating Data

To update data, y'all can use the same setValue() method by passing new value. You can too use updateChildren() by passing the path to update data without disturbing other child nodes data.

For example if you desire to update but the user e-mail, you can utilise below lawmaking block.

Cord newEmail = 'androidhive@gmail.com';  mDatabase.kid(userId).child("e-mail").setValue(newEmail);        

3.iv Deleting Data

To delete data, you can just call removeValue() method on to database reference. Yous tin also pass nothing to setValue() method which do the same delete operation.

You can learn more about performing Crud operations onto more than advanced data similar Lists of data here.

4. Security & Rules

Firebase rules provides a manner to identify user role while performing read and write operations. These rules will acts a security layer on the server before perform any Grime operation. By default the rules allows user to perform read & write performance only later on authentication.

The below rules allow authenticated users only to read or write data.

{   "rules": {     ".read": "auth != cypher",     ".write": "auth != null"   } }        

Beneath rules allows everyone to read & write data without authentication.

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

You can as well employ these rules to validate data before inserting into database. For instance below rules validates the name to be less than 50 chars and email to be valid using e-mail regular expression.

{ 	"rules": { 		".read": true, 		".write": true, 		"users": { 			"$user": { 				"proper name": { 					".validate": "newData.isString() && newData.val().length < 50" 				}, 				"email": { 					".validate": "newData.isString() && newData.val().matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{ii,4}$/i)" 				} 			} 		} 	} }        

Go through firebase security & rules guide to learn more well-nigh the security concepts.

Now nosotros have plenty knowledge to get started with an android project. Let'south create one and run across how to integrate the realtime database with an example app.

5. Creating Android Project

ane. Showtime thing you need to do is get to https://firebase.google.com/ and make an account to gain admission to their panel. After y'all proceeds access to the console you can start by creating your starting time projection.

two. Give the bundle name of your project (mine is info.androidhive.firebase) in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app push button.

android-creating-firebase-app

3. Create a new project in Android Studio from File ⇒ New Project. While filling the project details, use the aforementioned package name which you gave in firebase console. In my case I am using aforementioned info.androidhive.firebase.

iv. Paste the google-services.json file to your projection'southward app folder. This step is very important as your project won't build without this file.

five. Now open the build.gradle located in project's home directory and add together google playstore dependency.

dependencies {         classpath 'com.android.tools.build:gradle:two.2.0'         classpath 'com.google.gms:google-services:3.0.0'          // Notation: Exercise not identify your application dependencies here; they vest         // in the individual module build.gradle files     }        

6. Open up app/build.gradle and add firebase database dependency. At the very bottom of the file, add together utilise plugin: 'com.google.gms.google-services'

dependencies {     // Adding support library for this demo app     compile 'com.android.support:pattern:24.two.1'      compile 'com.google.firebase:firebase-database:9.6.one' }  apply plugin: 'com.google.gms.google-services'        

seven. In lodge to store user contour, we need a model class called User.java. Create a class named User.coffee and add below class backdrop. If Yous want y'all can add few more properties like address, mobile etc.,

package info.androidhive.firebase;  import com.google.firebase.database.IgnoreExtraProperties;  /**  * Created past Ravi Tamada on 07/x/16.  * www.androidhive.info  */  @IgnoreExtraProperties public class User {      public String proper noun;     public String email;      // Default constructor required for calls to     // DataSnapshot.getValue(User.grade)     public User() {     }      public User(String name, String electronic mail) {         this.name = name;         this.e-mail = electronic mail;     } }        

8. Open the layout file of principal activity activity_main.xml and add the below layout. This layout creates a unproblematic form where you can enter the profile data to store in database.

<?xml version="ane.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/activity_main"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context="info.androidhive.firebase.MainActivity">      <TextView         android:id="@+id/txt_user"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:paddingBottom="@dimen/activity_horizontal_margin"         android:paddingTop="@dimen/activity_horizontal_margin"         android:textSize="20dp" />      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:orientation="vertical">          <android.support.design.widget.TextInputLayout             android:layout_width="match_parent"             android:layout_height="wrap_content">              <EditText                 android:id="@+id/proper name"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:hint="@string/name"                 android:inputType="textCapWords"                 android:maxLines="1" />          </android.support.blueprint.widget.TextInputLayout>          <android.support.design.widget.TextInputLayout             android:layout_width="match_parent"             android:layout_height="wrap_content">              <EditText                 android:id="@+id/email"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:hint="@string/email"                 android:inputType="textEmailAddress"                 android:maxLines="1" />          </android.support.design.widget.TextInputLayout>          <Button             android:id="@+id/btn_save"             style="?android:textAppearanceSmall"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginTop="16dp"             android:background="@color/colorPrimary"             android:text="@string/action_save"             android:textColor="@android:color/white"             android:textStyle="bold" />      </LinearLayout>  </LinearLayout>        

9. Open up MainActivity.java and practise the below necessary changes. The code is very uncomplicated and easily understandable.

Our goal is to create the json structure as below in which 'app_title' stores the app title. 'users' stores user profiles as an assortment of nodes.

{   "app_title" : "Realtime Database",   "users" : {     "-KTYWvZG4Qn9ZYTc47O6" : {       "e-mail" : "ravi@androidhive.info",       "name" : "Ravi Tamada"     }   } }        

> getReference("app_title") create a node named app_title which stores the toolbar title.

> getReference("users") gets reference to users node.

> createUser() method stores a new user in realtime database

> updateUser() method updates user information like name and email.

bundle info.androidhive.firebase;  import android.bone.Bundle; import android.back up.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;  import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener;  public form MainActivity extends AppCompatActivity {      individual static last String TAG = MainActivity.class.getSimpleName();     individual TextView txtDetails;     private EditText inputName, inputEmail;     private Button btnSave;     private DatabaseReference mFirebaseDatabase;     private FirebaseDatabase mFirebaseInstance;      private String userId;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Displaying toolbar icon         getSupportActionBar().setDisplayShowHomeEnabled(true);         getSupportActionBar().setIcon(R.mipmap.ic_launcher);          txtDetails = (TextView) findViewById(R.id.txt_user);         inputName = (EditText) findViewById(R.id.name);         inputEmail = (EditText) findViewById(R.id.email);         btnSave = (Button) findViewById(R.id.btn_save);          mFirebaseInstance = FirebaseDatabase.getInstance();          // go reference to 'users' node         mFirebaseDatabase = mFirebaseInstance.getReference("users");          // store app championship to 'app_title' node         mFirebaseInstance.getReference("app_title").setValue("Realtime Database");          // app_title change listener         mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {             @Override             public void onDataChange(DataSnapshot dataSnapshot) {                 Log.e(TAG, "App title updated");                  String appTitle = dataSnapshot.getValue(String.course);                  // update toolbar title                 getSupportActionBar().setTitle(appTitle);             }              @Override             public void onCancelled(DatabaseError mistake) {                 // Failed to read value                 Log.due east(TAG, "Failed to read app title value.", error.toException());             }         });          // Save / update the user         btnSave.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 String name = inputName.getText().toString();                 String email = inputEmail.getText().toString();                  // Check for already existed userId                 if (TextUtils.isEmpty(userId)) {                     createUser(proper name, electronic mail);                 } else {                     updateUser(name, email);                 }             }         });          toggleButton();     }      // Irresolute button text     individual void toggleButton() {         if (TextUtils.isEmpty(userId)) {             btnSave.setText("Salvage");         } else {             btnSave.setText("Update");         }     }      /**      * Creating new user node under 'users'      */     private void createUser(String name, String email) {         // TODO         // In real apps this userId should exist fetched         // by implementing firebase auth         if (TextUtils.isEmpty(userId)) {             userId = mFirebaseDatabase.button().getKey();         }          User user = new User(name, e-mail);          mFirebaseDatabase.child(userId).setValue(user);          addUserChangeListener();     }      /**      * User data change listener      */     private void addUserChangeListener() {         // User data change listener         mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {             @Override             public void onDataChange(DataSnapshot dataSnapshot) {                 User user = dataSnapshot.getValue(User.class);                  // Check for null                 if (user == null) {                     Log.e(TAG, "User information is null!");                     render;                 }                  Log.e(TAG, "User data is changed!" + user.proper name + ", " + user.email);                  // Display newly updated name and e-mail                 txtDetails.setText(user.name + ", " + user.email);                  // clear edit text                 inputEmail.setText("");                 inputName.setText("");                  toggleButton();             }              @Override             public void onCancelled(DatabaseError error) {                 // Failed to read value                 Log.due east(TAG, "Failed to read user", fault.toException());             }         });     }      private void updateUser(String name, String e-mail) {         // updating the user via child nodes         if (!TextUtils.isEmpty(proper name))             mFirebaseDatabase.child(userId).kid("name").setValue(proper noun);          if (!TextUtils.isEmpty(email))             mFirebaseDatabase.child(userId).child("email").setValue(electronic mail);     } }        

Run & exam the app once. Yous should exist able to run into the changes in realtime in your firebase panel. Cheque the Demo video that shows how to run and test the app.

android-firebase-realtime-database

6. Pricing

Unlike Analytics, Deject Messaging, Crash Reporting and other services, firebase realtime database is not completely free. There are sure limitations in Free plan. You lot demand to pay few bucks for the usage of number of connections, disk usage and network usage. For more information check out the firebase pricing plans.

Hither is the quick overview of realtime database pricing details (as of Oct 12th, 2016)

Realtime Database Pricing

Complimentary $25 per calendar month Pay as you go
Simultaneous connections 100 Unlimited Unlimited
GB stored 1 GB 2.5 GB $5/GB
GB downloaded 10 GB twenty GB $i/GB
Daily private backups No Aye Yes

7. References

Security rules:
https://firebase.google.com/docs/database/security/quickstart#sample-rules

Firebase Blog
https://firebase.googleblog.com/2016/07/have-you-met-realtime-database.html

powellflaul1960.blogspot.com

Source: https://www.androidhive.info/2016/10/android-working-with-firebase-realtime-database/

Post a Comment for "Random Matching of Users Firebase and Not Matched Again"