MASIGNCLEAN101

Phones gallery [part 06] | Android studio save user info into firebase database

Welcome back to the "Phones gallery" series, in this part we will save the user info inside the firebase database.So lets get started :

Firebase database setup

First, we need to setup firebase database so:
  • First of all you need to go to firebase console by clicking here.
  • Choose your project (if it is your first project then you will find one project).
  • In the left side click on Realtime database
        • Click on create database
        • Choose the database location (you can't change this later) and click next
        • For now select test mode and click enable
        • Now your database is ready lets write some code..

        Dependencies

        Allwrite we need the realtime database dependencies :
        1. Go to android studio, open your project.
        2. In the left side click on Project in order to open project files
        3. Expand Gradle scripts and open build.gradle (Module)
        4. Add this line inside your dependencies
        implementation 'com.google.firebase:firebase-database:20.0.1'

        GoogleUserInfo.java

        So you need to know that the info we will get it from the google login are : email , first name, second name, account type and and phone number (we need to check if there is a phone number and if there is not we will put "No number" instead).
        Here my "GoogleUserInfo.java" file :
        package m.phonesgallery.phonesgallery.helpers;

        public class GoogleUserInfo {
        String firstName,secondName,email,phoneNumber,accountType;

        public GoogleUserInfo(String firstName, String secondName, String email, String phoneNumber, String accountType) {
        this.firstName = firstName;
        this.secondName = secondName;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.accountType = accountType;
        }

        public String getFirstName() {
        return firstName;
        }

        public void setFirstName(String firstName) {
        this.firstName = firstName;
        }

        public String getSecondName() {
        return secondName;
        }

        public void setSecondName(String secondName) {
        this.secondName = secondName;
        }

        public String getEmail() {
        return email;
        }

        public void setEmail(String email) {
        this.email = email;
        }

        public String getPhoneNumber() {
        return phoneNumber;
        }

        public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
        }

        public String getAccountType() {
        return accountType;
        }

        public void setAccountType(String accountType) {
        this.accountType = accountType;
        }
        }

        Login.java

        In the last part we implement the google login so in this part we will continue in the same file Login.java to save the user info inside the database.
        Here my Login.java file updated from part 5:
        package m.phonesgallery.phonesgallery;

        import androidx.annotation.NonNull;
        import androidx.annotation.Nullable;
        import androidx.appcompat.app.AppCompatActivity;

        import android.content.Intent;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Toast;

        import com.google.android.gms.auth.api.signin.GoogleSignIn;
        import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
        import com.google.android.gms.auth.api.signin.GoogleSignInClient;
        import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
        import com.google.android.gms.common.SignInButton;
        import com.google.android.gms.common.api.ApiException;
        import com.google.android.gms.tasks.OnFailureListener;
        import com.google.android.gms.tasks.OnSuccessListener;
        import com.google.android.gms.tasks.Task;
        import com.google.firebase.auth.AuthCredential;
        import com.google.firebase.auth.AuthResult;
        import com.google.firebase.auth.FirebaseAuth;
        import com.google.firebase.auth.FirebaseUser;
        import com.google.firebase.auth.GoogleAuthProvider;
        import com.google.firebase.database.DatabaseReference;
        import com.google.firebase.database.FirebaseDatabase;

        import m.phonesgallery.phonesgallery.helpers.GoogleUserInfo;
        import m.phonesgallery.phonesgallery.helpers.LoadingDialog;

        public class Login extends AppCompatActivity {

        //XML
        SignInButton googleBtn;

        //Helpers
        private final int RC_SIGN_IN = 1;
        GoogleSignInClient googleSignInClient;

        //firebase
        FirebaseAuth firebaseAuth;

        //Dialogs
        LoadingDialog loadingDialog;

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

        //XML
        googleBtn = findViewById(R.id.googleBtn);

        //firebase
        firebaseAuth = FirebaseAuth.getInstance();

        //Dialogs
        loadingDialog = new LoadingDialog(this);

        //Google login
        googleLoginHelper();
        googleBtn.setOnClickListener(this::googleClick);


        }



        private void googleLoginHelper() {
        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions
        .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();

        googleSignInClient = GoogleSignIn.getClient(this,googleSignInOptions);
        }

        private void googleClick(View view) {
        Intent signInIntent = googleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent,RC_SIGN_IN);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN){
        loadingDialog.start();
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
        //Login successfull
        GoogleSignInAccount account = task.getResult(ApiException.class);
        FirebaseAuthWithGoogle(account.getIdToken());
        } catch (ApiException e) {
        //login Failed
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        loadingDialog.end();
        }
        }
        }

        public void FirebaseAuthWithGoogle(String idToken){
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken,null);
        firebaseAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
        @Override
        public void onSuccess(AuthResult authResult) {
        //the authentication is done we will continue this next part
        saveToDatabase();
        }
        }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
        //the authentication failed we must stop the dialog
        loadingDialog.end();
        Toast.makeText(Login.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        });
        }

        private void saveToDatabase() {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        assert user!= null;
        String firstName = user.getDisplayName();
        String secondName = user.getDisplayName();
        String email = user.getEmail();
        String phoneNumber = user.getPhoneNumber();
        String accountType = "Google account";

        if (phoneNumber == null){
        phoneNumber = "No phone number";
        }
        GoogleUserInfo googleUserInfo = new GoogleUserInfo(firstName,secondName,email,phoneNumber,accountType);
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference reference = database.getReference("Users");
        reference.child(user.getUid()).setValue(googleUserInfo).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
        loadingDialog.end();
        startActivity(new Intent(Login.this,Main.class));
        finish();
        }
        });

        }
        }

        Youtube

        Watch the youtube video for more info :
        Thanks for watching


        Rio Ilham Hadi

        MEDDAHI Fares is a Nurse, android apps developper, content creator and the owner of M-ify. Algerian and 20 years old.

        About website

        M-ify is an educational website interested in technology in general and programming in particular. We aim through this site to deliver information to the visitor in a very easy and simplified manner. What are you waiting for M-ify is your easy way to learn.