In this post we will learn about Firebase User Authentication or Signin. If you have read the last tutorial about Firebase Authentication then you already know that in the last tutorial we covered the User Registration part using Firebase. In this Firebase User Authentication tutorial we will create a login option in our app using Email and Password.
First I will recommend you to go through the last tutorial from the below link, as I will be working on the same project.
Firebase User Authentication Video Tutorial
Modifying the User Registration Screen
If you don’t want to read the tutorial, just view this 20 minutes youtube video.
Firebase User Authentication Tutorial
- First open the last project we created.
- Go inside activity_main.xml and change the layout as follows. We are adding a TextView where user can click to go to the login activity directly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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="net.simplifiedcoding.firebaseauthdemo.MainActivity"> <LinearLayout android:layout_centerVertical="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="User Registration" android:id="@+id/textView" android:layout_gravity="center_horizontal" /> <EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:hint="Enter email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:hint="Enter password" android:inputType="textPassword" /> <Button android:id="@+id/buttonSignup" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:text="Signup" /> <TextView android:text="Already Registered? Signin Here" android:id="@+id/textViewSignin" android:textAlignment="center" android:layout_margin="15dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout> |
- Now your Activity will look as follow in the preview.
- Now come inside MainActivity.java and modify your code as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
package net.simplifiedcoding.firebaseauthdemo; import android.app.ProgressDialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //defining view objects private EditText editTextEmail; private EditText editTextPassword; private Button buttonSignup; private TextView textViewSignin; private ProgressDialog progressDialog; //defining firebaseauth object private FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initializing firebase auth object firebaseAuth = FirebaseAuth.getInstance(); //if getCurrentUser does not returns null if(firebaseAuth.getCurrentUser() != null){ //that means user is already logged in //so close this activity finish(); //and open profile activity startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } //initializing views editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); textViewSignin = (TextView) findViewById(R.id.textViewSignin); buttonSignup = (Button) findViewById(R.id.buttonSignup); progressDialog = new ProgressDialog(this); //attaching listener to button buttonSignup.setOnClickListener(this); textViewSignin.setOnClickListener(this); } private void registerUser(){ //getting email and password from edit texts String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); //checking if email and passwords are empty if(TextUtils.isEmpty(email)){ Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show(); return; } if(TextUtils.isEmpty(password)){ Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show(); return; } //if the email and password are not empty //displaying a progress dialog progressDialog.setMessage("Registering Please Wait..."); progressDialog.show(); //creating a new user firebaseAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { //checking if success if(task.isSuccessful()){ finish(); startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); }else{ //display some message here Toast.makeText(MainActivity.this,"Registration Error",Toast.LENGTH_LONG).show(); } progressDialog.dismiss(); } }); } @Override public void onClick(View view) { if(view == buttonSignup){ registerUser(); } if(view == textViewSignin){ //open login activity when user taps on the already registered textview startActivity(new Intent(this, LoginActivity.class)); } } } |
- Now we will create the Profile Activity.
Adding Profile Activity to Project
- Right click on package and create new activity named ProfileActivity.
- Inside the layout file of this activity write the following xml code. (In my case it is activity_profile.xml)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" 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="net.simplifiedcoding.firebaseauthdemo.ProfileActivity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerVertical="true" android:layout_centerHorizontal="true"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="@+id/textViewUserEmail" android:layout_gravity="center_horizontal" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Logout" android:id="@+id/buttonLogout" android:layout_gravity="center_horizontal" /> </LinearLayout> </RelativeLayout> |
- We haven’t done much on this activity as it contains a TextView and a Button only. In TextView we will show the logged in user email and the button will be used for logout.
- The above XML code will show you the following layout.
- Now come inside ProfileActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
package net.simplifiedcoding.firebaseauthdemo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class ProfileActivity extends AppCompatActivity implements View.OnClickListener { //firebase auth object private FirebaseAuth firebaseAuth; //view objects private TextView textViewUserEmail; private Button buttonLogout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //initializing firebase authentication object firebaseAuth = FirebaseAuth.getInstance(); //if the user is not logged in //that means current user will return null if(firebaseAuth.getCurrentUser() == null){ //closing this activity finish(); //starting login activity startActivity(new Intent(this, LoginActivity.class)); } //getting current user FirebaseUser user = firebaseAuth.getCurrentUser(); //initializing views textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail); buttonLogout = (Button) findViewById(R.id.buttonLogout); //displaying logged in user name textViewUserEmail.setText("Welcome "+user.getEmail()); //adding listener to button buttonLogout.setOnClickListener(this); } @Override public void onClick(View view) { //if logout is pressed if(view == buttonLogout){ //logging out the user firebaseAuth.signOut(); //closing activity finish(); //starting login activity startActivity(new Intent(this, LoginActivity.class)); } } } |
- Now we will add Login Activity to our project.
Adding Login Activity to Project
- Again right click on package and new -> activity -> empty activity, and create a new Activity. Name it LoginActivity.
- Inside the layout file of this activity activity_login.xml write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" 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="net.simplifiedcoding.firebaseauthdemo.LoginActivity"> <LinearLayout android:layout_centerVertical="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="User Login" android:id="@+id/textView" android:layout_gravity="center_horizontal" /> <EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:hint="Enter email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:hint="Enter password" android:inputType="textPassword" /> <Button android:id="@+id/buttonSignin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:text="Signup" /> <TextView android:text="Not have an account? Signup Here" android:id="@+id/textViewSignUp" android:textAlignment="center" android:layout_margin="15dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout> |
- You will see the following layout in preview.
- Now lets code this activity, so come inside LoginActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
package net.simplifiedcoding.firebaseauthdemo; import android.app.ProgressDialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class LoginActivity extends AppCompatActivity implements View.OnClickListener { //defining views private Button buttonSignIn; private EditText editTextEmail; private EditText editTextPassword; private TextView textViewSignup; //firebase auth object private FirebaseAuth firebaseAuth; //progress dialog private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //getting firebase auth object firebaseAuth = FirebaseAuth.getInstance(); //if the objects getcurrentuser method is not null //means user is already logged in if(firebaseAuth.getCurrentUser() != null){ //close this activity finish(); //opening profile activity startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } //initializing views editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); buttonSignIn = (Button) findViewById(R.id.buttonSignin); textViewSignup = (TextView) findViewById(R.id.textViewSignUp); progressDialog = new ProgressDialog(this); //attaching click listener buttonSignIn.setOnClickListener(this); textViewSignup.setOnClickListener(this); } //method for user login private void userLogin(){ String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); //checking if email and passwords are empty if(TextUtils.isEmpty(email)){ Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show(); return; } if(TextUtils.isEmpty(password)){ Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show(); return; } //if the email and password are not empty //displaying a progress dialog progressDialog.setMessage("Registering Please Wait..."); progressDialog.show(); //logging in the user firebaseAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressDialog.dismiss(); //if the task is successfull if(task.isSuccessful()){ //start the profile activity finish(); startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } } }); } @Override public void onClick(View view) { if(view == buttonSignIn){ userLogin(); } if(view == textViewSignup){ finish(); startActivity(new Intent(this, MainActivity.class)); } } } |
- Thats it now just run your app go to login and try logging in.
- Bingo! it is working absolutely fine. You can also get the source code from the link given below.
[sociallocker id=1372] Firebase User Authentication Example [/sociallocker]
So thats all for this Firebase User Authentication Example friends. In the next Firebase User Authentication Tutorial we will do some more operations like password reset, email change, account deletion etc. And don’t forget to share this Firebase user Authentication Tutorial among your friends. Thank You 🙂