Android App Development | Lecture#33 | Part-2 | Hive Learners

𝓖𝓻𝓮𝓮𝓽𝓲𝓷𝓰𝓼

eating to all the members of Hive Learner and to the whole Hive family. I hope you all are well. Today we will start part 2 of Firebase Authentication. We cover the basic setup of the firebase in our project and add the project to the firebase console. Now we are ready to write some logic to create a user account. So let's get started.

GitHub Link

Use this GitHub project to clone into your directory. The following lecture will constantly update it so you will never miss the latest code. Happy Coding!

What Should I Learn

  • How to create a User in Firebase
  • Save user information

Assignment

  • Create a sign-up logic using Firebase Authentication.

Procedure

In Part 1 we initialize and declare the FirebaseAuth object now we will use it to create an account of the user with the provided credentials. We will use createUserWithEmailAndPassword with the Listeners to check if the account was created successfully or not and show the message or progress bar. We will write the code in the sign-up button click listener.

 signup_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String email = email_et.getText().toString().toLowerCase().trim();
                String password = pass_et.getText().toString();
                String username = name_et.getText().toString();

                if (TextUtils.isEmpty(username)) {
                    name_et.setError("Invalid Name");
                    return;
                }
                if (TextUtils.isEmpty(email)) {
                    email_et.setError("Invalid Email");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    pass_et.setError("Invalid Password");
                    return;
                }
                if (!(password.equals(confirm_pass_et.getText().toString()))) {
                    Toast.makeText(Signup_Activity.this, "Password not matching", Toast.LENGTH_SHORT).show();
                    return;
                }

                firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                    }
                });

            }
        });

We can replisteners'eners code with lambda as we are using JAVA 1.8. It will reduce the code and become easy to read. Press ALT+ENTER on the fade part of the Listener and click on

You can change every possible part to lamda as shown here after the replacement the code is reduced and more readable.

Here is the empty code that will never show any message I use the comments in the logic. We will add the progress dialog for it and show a success Alert dialog with a button.

Declare and initialize the ProgressDialog and AlertDialog.

Now we can write the code for the Progress Dialog. Set the message after the check and show it. In the listener, if failed or successful we need to cancel the Progress Dialog with a check isShowing().

Here we write the code for the Alert Dialog to show a success or fail message.

firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {

                    if (progressDialog.isShowing())
                        progressDialog.cancel();

                    alertDialog.setTitle("Done");
                    alertDialog.setMessage("Your account is created successfully");
                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", (dialog, which) -> {
                        dialog.cancel();

                    });
                    alertDialog.setCancelable(false);
                    alertDialog.show();

                    //Sig up Successful
                } else {

                    if (progressDialog.isShowing())
                        progressDialog.cancel();

                    alertDialog.setTitle("Failed");
                    alertDialog.setMessage(task.getException().getMessage());
                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", (dialog, which) -> {
                        dialog.cancel();

                    });
                    alertDialog.show();
                    // Sign up failed
                }

            });

We also need to store the username of this user. It is a tricky part. We will use the FirebaseUser and use its listners. Its success then shows the success message. But if failed we need to delete the created account to show the failed dialog. There is a 1% case of failure and it will be due to an internet connection. We also need to sign out the user after the account is successfully created.

firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                            .setDisplayName(username)
                            .build();
                    assert user != null;
                    user.updateProfile(profileUpdates)
                            .addOnCompleteListener(task1 -> {
                                if (task1.isSuccessful()) {
                                    firebaseAuth.signOut();
                                    if (progressDialog.isShowing())
                                        progressDialog.cancel();
                                    alertDialog.setTitle("Done");
                                    alertDialog.setMessage("Your account is created successfully");
                                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", (dialog, which) -> {

                                        dialog.cancel();

                                    });
                                    alertDialog.setCancelable(false);
                                } else {

                                    // Delete the account if username not save successfully to let the user retry
                                    assert firebaseAuth.getCurrentUser() != null;
                                    firebaseAuth.getCurrentUser().delete();
                                    alertDialog.setTitle("Failed");
                                    alertDialog.setMessage(task1.getException().getMessage());
                                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", (dialog, which) -> {
                                        dialog.cancel();

                                    });
                                }
                                alertDialog.show();
                            });


                    //Sig up Successful
                } else {

                    if (progressDialog.isShowing())
                        progressDialog.cancel();

                    alertDialog.setTitle("Failed");
                    alertDialog.setMessage(task.getException().getMessage());
                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", (dialog, which) -> {
                        dialog.cancel();

                    });
                    alertDialog.show();
                    // Sign up failed
                }

            });

Now our logic the complete. But we have no button in Main_Activity. by default Main Activity will load so we need to set two buttons in Main Activity for now to open the signup and signing page.

Also, write its java code.

Now run the app and signup.


hl_divider.png

Thank You

hl_footer_banner.png



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000