Create Real-time Firebase Database For Your Android App

How to Create Real-time Database With Firebase For Your Android App?

0
Shares
How to Create Real-time Database With Firebase For Your Android App?
3 (60%) 2 votes

cloud security with firebase Android

Today, majority of apps need backend.

In fact, if you create a simple tic-tack-toe game for smartphone, it would require a backend to provide your app a board for scores or multiplayer feature.

Now, you might find few mobile apps which are backendless, but they’re a minority.

Nevertheless, Google I/O recently launched new and upgraded real-time Firebase database.

To the newly arrived developers, Firebase database is a cloud-hosted NoSQL database. This means, Firebase is a kind of database that does not use tables and this tableless database does not store its data locally on the device, but stores them in the cloud, hence the label “RealTime”.

The main benefit of this is that your users’ application data will be available from any device that login with same credential.

Not only that, It has other capabilities too.

firebase-key-capabilities

Now, to demonstrate how easy and simple to use Firebase is, we’re going to create android app demo with  login/register (with Firebase authentication) by using Firebase Email & Password authentication.

And if you don’t know what Firebase database is, It basically offers a set of authentication option right out-of-the-box. It means, Firebase automatically save your app users’ credentials (using bcrypt). It is actually a good benefit for Android developers as it separates user credentials from application data and allows you to focus on user interface & experience of your Android app.

Implementing Firebase Authentication

Create a new project under the file menu and name it. Here, we’re naming it as Firebase Database Demo.

ImagePicker1

In the following tab, select your Form Factor in which you want to develop your app.

ImagePicker2

In the following tab, select Empty Activity and click on Next button.

ImagePicker3

In the last tab, write Activity name for your app project and click on Finish button.

ImagePicker4

Once you create a project in Android Studio, it’s time to create a new project on Firebase Console.

First, you need to go to https://firebase.google.com/ and make an account to gain access to Firebase console. After you gain access to the console, you can start by creating your first project.

ImagePicker5

After you create a new project in Firebase, Setup Sign-In method by using email and password.

ImagePicker6

 

ImagePicker7

 

ImagePicker8

After setting up the Sign-In method, open Firebase tools. (Android Studio 2.2 Tools -> Firebase)

ImagePicker9

Now implement authentication with following steps show in images below.

ImagePicker10

ImagePicker11

ImagePicker12

Next, after implementing authentication, you need to implement Real-time Database.

ImagePicker13

 

ImagePicker14

ImagePicker15

Once you add the Real-time database, set the database security rules.

ImagePicker16

Done! Now let’s move to code part. Open your project in Android Studio.

AppController.java

//initialize Firebase sdk in application class

FirebaseApp.initializeApp(getApplicationContext());

SignUpActivity.java

//initialize FirebaseAuth Ref
mAuth = FirebaseAuth.getInstance();

//Create User for Authentication
showProgress();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final FirebaseUser userInfo = task.getResult().getUser();
if (userInfo != null) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
DatabaseReference database = FirebaseDatabase.getInstance().getReference("users");
database = database.child(userInfo.getUid());
final UserModel userModel = new UserModel();
userModel.setFirst_name(firstName);
userModel.setLast_name(lastName);
userModel.setEmail(email);
userModel.setMobile_number(mobileNumber);
database.setValue(userModel);
database.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
hideProgress();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (null != user) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finishAffinity();
Toast.makeText(SignUpActivity.this, "Your registration has been successfully done.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
hideProgress();
Log.d("==>","==>"+databaseError);
}
});
} else {
hideProgress();
Utility.alert(SignUpActivity.this, null, task.getException().getMessage());
}
}
});
} else {
hideProgress();
Utility.alert(SignUpActivity.this, null, task.getException().getMessage());
}
} else {
hideProgress();
Utility.alert(SignUpActivity.this, null, task.getException().getMessage());
}
}
});

LoginActivity.java

//initialize FirebaseAuth Ref
mAuth = FirebaseAuth.getInstance();


//Sign in via email id and password
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
hideProgress();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (null != user) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
} else {
hideProgress();
Utility.alert(LoginActivity.this, null, task.getException().getMessage());
}
}
});

MainActivity.java

//Retrive Data from Firebase Database
showProgress();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference database = FirebaseDatabase.getInstance().getReference("users");
database = database.child(user.getUid());
database.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
hideProgress();
UserModel userModel = dataSnapshot.getValue(UserModel.class);
((TextView) findViewById(R.id.textView)).setText("Hello " + userModel.getFirst_name() + " " + userModel.getLast_name());
}
@Override
public void onCancelled(DatabaseError databaseError) {
hideProgress();
Log.d("==>", "==>" + databaseError);
}
});

And that’s how it’s done!

So, now that you know the basics to create a simple login/register Android app with Firebase, you can continue exploring its features. If you face any problem in this demo, you can contact our developers for help.

And with super easy and quick to implement Firebase database, there is no need of server side configuration, PHP scripts, and Database designs. You can easily store users’ credentials securely and redundantly with Firebase.

You can directly download Firebase tutorial Android from our GitHub account.

However, if you need help implementing Firebase Database in your native Android app and searching for Android app development company, contact us.

 
0
Shares
 

Want to Create a Real-time App? Contact us Now.

Get your free consultation now