Retrieve data from Firebase Realtime Database in Android – 2020

by | Feb 7, 2020 | Android, Android Firebase Tutorials, Android UI/UX Tutorials, Bull's Rent, Database, UI UX | 0 comments

This tutorial is about to retrieve data from Firebase Realtime Database in Android Studio.

Also, you will learn about how to validate username and password fields using regex in the android studio.

This is the 2nd part of our android studio firebase tutorial.

In the 1st part, you will learn how to store data in the firebase database in an android studio.

Get the complete Bull’s Rent project.

Button’s OnClick

To call OR use the button’s onClick function we have to simply follow this approach instead of calling the setOnClickListner.

We will first create a function in Java outside onCreate method and it should be public, and contain View Parameter as mentioned below.

public void registerUser(View view) {}

Now to call that function we have to mention it behind the button’s onClick XML code so, compiler will know that when user presses the button which method to be executed. So, we will add the code written below behind the button’s XML


android:onClick="registerUser"

<Button
    android:id="@+id/reg_btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#000"
    android:onClick="registerUser"
    android:text="GO"
    android:textColor="#fff"
    android:transitionName="button_tran" />

YouTube Video To Retrieve Data From Firebase

What is Firebase?

Firebase is a NoSQL database. It frees developers to focus on the user experience. All the things in firebase are generical. You have to modify or arrange them as per your needs. Firebase is a web and app development platform. It serves developers with a lot of services to make app and web more quality.

Firebase also provides some tools to the developers. In which it covers a lot of portions itself rather developers have to make by themself. It takes a lot of time instead. The following are the Tools used in Firebase Database.

 

Tools Include

  • Authentication
  • RealTime database
  • Storage
  • Cloud messaging
  • Hosting
  • Test Lab
  • Push messaging

What is Realtime Database?

A Realtime database is a cloud-hosted database.It’s also called NOSQL database.In this realtime. HTTP make calls to get data and store data in firebase  database.

Connection between firebase an app is HTTP .Then you become connected through WEBSOCKET.You dont have to make calls , by single call all of your data sync automatically.

Syncing make it easy for users to access , store ,retrieve data from anywhere weather it is mob or web.Fetching data from firebase is so easy for users now.

One more very big advantage the realtime firabase give user is , when you are offline and doing your work. It save data in realtime database SDK use local cache on your desktop.

when you become online again. All the data that is stored in local cache. Synchronized automatically and save data in realtime database firebase.

Steps retrieve data from Firebase

1-Start Android Studio

Open the android studio first.you can download it by clicking on the link.

Design activity XML splash screen

If you guys don’t know, how to make the design. You can check aur previous tutorial of Material design sign up

2-Create Activity Login.java

After we open the android studio successfully then we have to make an activity that is Login.java.

In this activity when we click on the Go button. Insight sign-in screen, a function “login user”, is called in which we have to validate user name and password.

 public void loginUser(View view) {
        //Validate Login Info 
        if (!validateUsername() | !validatePassword()) {
        return;
    } 
    }

3-Validate Username

Now we have to validate “Username”.

First of all, make a Boolean function “ValidateUsername()”.

In this function, we have to make sure that the username field is not empty and have not extra spaces because if there is a space between username, so it will give an error message.

To make this we will write “username.setenabled{false}” as shown in the code below.

It also takes aur material design to the original position.

 private Boolean validateUsername() {
        String val = username.getEditText().getText().toString();
        if (val.isEmpty()) {
        username.setError("Field cannot be empty");
        return false;
    } else {
        username.setError(null);
        username.setErrorEnabled(false);
        return true;
    }
    }

4-Validate Password

In this function, first. We make a function of “ValidatePassword”, in this we have to check the field are not empty.  It matches the password, which the user entered.

if you want to check to validate password in signup screen, so you can check the link

 

private Boolean validatePassword() {
        String val = password.getEditText().getText().toString();
        if (val.isEmpty()) {
        password.setError("Field cannot be empty");
        return false;
    } else {
        password.setError(null);
        password.setErrorEnabled(false);
        return true;
    }
    }

5- Login User

Again come to the “Loginuser” , check both “ValidateUsername ()” and “ValidatePassword()” are empty or not .

Once they both validate, in else, we will make another function “isUser”.

This function will fetch the data from Firebase of the specific user. If there are some users related to this user and then we will fetch password details to match it with the password entered by the user.

public void loginUser(View view) {
        //Validate Login Info 
        if (!validateUsername() | !validatePassword()) {
        return;
    } else {
        isUser();
    }
    }

6- Get User entered value

We will make the function of “isUser()”, in this we will get the user entered values Username and Password in String like this in code below.

 final String userEnteredUsername = username.getEditText().getText().toString().trim();
final String userEnteredPassword = password.getEditText().getText().toString().trim();

So to start working on the Firebase, we first need to create Firebase Reference, so call the Database reference.

After that, we have to go to the fire database and go to the instance but we have to keep in mind that, we have a reference with name users.  So the reference is pointing  to the users like below in code

DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");

Then we have to add Query with the first one with a firebase and database.  This query look inside the username for all the users and match it with the value entered by the user.

Query checkUser = reference.orderByChild("username").equalTo(userEnteredUsername);

After this we will check the user-entered value by “addlistnerforsinglevalueevent” and it will give us two methods.

  •  ondatachange()
  •  oncancelled()

In data change,aur data is in data snapshot. Firstly we need to check if there is some data inside the data snapshot because  if the data exist we have to get data in string, like this

String passwordFromDB = dataSnapshot.child(userEnteredUsername).child("password").getValue(String.class);

how  to store and retrieve data from firebase

Once we will get the password or retrieve it from firebase data. We will check if the password from the database equals the password entered by the user. If they are equal so the user entered the right password.

Once this is authenticated, we will get the fields on firebase. But we have to make sure that we have to write the name exactly like written in firebase like this, we easily retrieve data from firebase.

Then we have to fetch data from Firebase by fetching values and storing data in the string variables like this below

nameFromDB = dataSnapshot.child(userEnteredUsername).child("name").getValue(String.class);
 String usernameFromDB = dataSnapshot.child(userEnteredUsername).child("username").getValue(String.class);
 String phoneNoFromDB = dataSnapshot.child(userEnteredUsername).child("phoneNo").getValue(String.class);
 String emailFromDB = dataSnapshot.child(userEnteredUsername).child("email").getValue(String.class);

After getting values from Firebase, or to pass these values or called another activity we have to write “intent”.  Put all the data inside the intent and then simply “start an activity()” and pass intent in it “start activity(intent)”.

If in the case password gets wrong, we cant retrieve data from firebase.  Then we will move to the else section because then we call password .seterror(“wrong password”).

And if there is no data inside of aur snapshot then we make another else “username.terror(“no username exist”).

 private void isUser() {
        progressBar.setVisibility(View.VISIBLE);
        final String userEnteredUsername = username.getEditText().getText().toString().trim();
        final String userEnteredPassword = password.getEditText().getText().toString().trim();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
        Query checkUser = reference.orderByChild("username").equalTo(userEnteredUsername);
        checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    username.setError(null);
                    username.setErrorEnabled(false);
                    String passwordFromDB = dataSnapshot.child(userEnteredUsername).child("password").getValue(String.class);
                    if (passwordFromDB.equals(userEnteredPassword)) {
                        username.setError(null);
                        username.setErrorEnabled(false);
                        String nameFromDB = dataSnapshot.child(userEnteredUsername).child("name").getValue(String.class);
                        String usernameFromDB = dataSnapshot.child(userEnteredUsername).child("username").getValue(String.class);
                        String phoneNoFromDB = dataSnapshot.child(userEnteredUsername).child("phoneNo").getValue(String.class);
                        String emailFromDB = dataSnapshot.child(userEnteredUsername).child("email").getValue(String.class);
                        Intent intent = new Intent(getApplicationContext(), UserProfile.class);
                        intent.putExtra("name", nameFromDB);
                        intent.putExtra("username", usernameFromDB);
                        intent.putExtra("email", emailFromDB);
                        intent.putExtra("phoneNo", phoneNoFromDB);
                        intent.putExtra("password", passwordFromDB);
                        startActivity(intent);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        password.setError("Wrong Password");
                        password.requestFocus();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    username.setError("No such User exist");
                    username.requestFocus();
                }
            }

7- Run the application

Run the application sign in material design mobile will appear on your screen .Write user name and password and click on GO button.

After clicking on GO button a new user profile screen appear on the screen.where we have to retrieve data from firebase and show it in the fields.

8- User Profile

In the user profile like above in the picture. We want to retrieve data from the firebase of the specific user in the fields.So for that we just have to retrieve all the data from Login and receive it in user profile because without that we can’t show data in userprofile.

Then we have to create hooks in user profile like this code

  //Hooks 
        fullName = findViewById(R.id.full_name_profile);
        email = findViewById(R.id.email_profile);
        phoneNo = findViewById(R.id.phone_no_profile);
        password = findViewById(R.id.password_profile);
        fullNameLabel = findViewById(R.id.fullname_field);
        usernameLabel = findViewById(R.id.username_field);

Show user data

Further onwards, we have to create a function of “showalluserdata()”. In this method we have to get retrieve data from the intent, and inside the intent, we need string values to show data in user profile. But keep in mind that the name, email phone, password are the same as in login activity.

 private void showAllUserData() {
        Intent intent = getIntent();
        String user_username = intent.getStringExtra("username");
        String user_name = intent.getStringExtra("name");
        String user_email = intent.getStringExtra("email");
        String user_phoneNo = intent.getStringExtra("phoneNo");
        String user_password = intent.getStringExtra("password");

Set data on text fields

 fullNameLabel.setText(user_name);
usernameLabel.setText(user_username);
fullName.getEditText().setText(user_name);
email.getEditText().setText(user_email);
phoneNo.getEditText().setText(user_phoneNo);
password.getEditText().setText(user_password);

9-Retrieve data from firebase

When we run the application set user name and password and click GO,  User profile activity appears like the pic given below. Data retrieve from the firebase of the user in the profile screen.

Get Complete Source code for Bull’s Rent App

CODING with T

🚀 Supercharge your Flutter skills! Subscribe to my YouTube channel now for mind-blowing coding insights, expert tips, and exclusive content. Don’t miss out!

COURSES

Android firebase app - android app 2022 - firebase android app - bulls rent app - coding with t app - android app
android complete login signup product by taimoor sikander free for any type of android app
Flutter E Commerce App Modern and latest
Flutter Login App UI Source Code - Flutter Complete App - Flutter App Design - Flutter App 2023 - Complete Flutter App 2023
Learn flutter from scratch in 4 hours - Flutter Crash Course - Coding with T

Latest Tutorial

How to create a Custom Appbar in flutter. Custom Appbar Design. Flutter App Design
How to create a Custom Shape in Flutter. Flutter E Commerce app Design. Ecommerce app design Flutter. Flutter clippath tutorial
Bottom Navigation bar in Flutter. Flutter Material 3 bottom navigation bar. How to design background color of Flutter bottom navigation bar. Flutter ecommerce app design