How to Register and Login in Android using Firebase ?
Hi.. In this tutorial we will learn about firebase Authentication with Email and Password. In this tutorial first we Register a user using email and then a email will sent to Email ID of that user then user have to verify that email otherwise, the user is unable to login into their app.
Output:-
Step 1:- Create a new Android project.
Step 2:- Connect your Project with firebase. You can connect your project with android studio tools and manually
Step 3:- To connect your project with firebase with Android Studio Click on Tools and then select Option Firebase.
Step 4:- Select Authentication and click on email and password authentication.
Step 5:- Click on Connect to Firebase and add some necessary libraries in your android project.
Now your Android project is Connected with the Firebase its time to write some code Let's get started
Create Login activity design i named it as activity_main you can give whatever you want to give not necessary.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/ProgressBarr"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/TV_PleaseWait"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PleaseWait..."
android:textSize="25sp"
android:layout_alignBottom="@id/ProgressBarr"
android:layout_alignRight="@id/ProgressBarr"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:padding="30dp">
<!--<ImageView
android:id="@+id/ImageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="@drawable/ic_account_circle_black_24dp"
android:padding="15dp"/>-->
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_marginTop="5dp">
<EditText
android:id="@+id/UserEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:ems="10"
android:inputType="text"
android:textSize="22sp"
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_marginTop="5dp"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/UserPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:ems="10"
android:inputType="textPassword"
android:textSize="22sp"
/>
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/Btn_Login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="22sp"
android:background="@drawable/btnbg"
android:layout_marginTop="40dp"
android:textColor="#fff"/>
<Button
android:id="@+id/Register_Here"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
android:background="@drawable/btnbg"
android:textSize="22sp"
android:layout_marginTop="40dp"
android:textColor="#fff"
/>
</LinearLayout>
</RelativeLayout>
Now Create Register Activity for your Registration.
activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="30dp"
tools:context=".RegisterActivity">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_marginTop="5dp">
<EditText
android:id="@+id/et_FullName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Full Name"
android:ems="10"
android:inputType="text"
android:textSize="22sp"
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:layout_marginTop="5dp"
android:focusableInTouchMode="true"
>
<EditText
android:id="@+id/et_Email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:ems="10"
android:inputType="text"
android:textSize="22sp"
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:layout_marginTop="5dp"
app:passwordToggleEnabled="true"
android:focusableInTouchMode="true"
>
<EditText
android:id="@+id/et_Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:ems="10"
android:inputType="textPassword"
android:textSize="22sp"
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:layout_marginTop="5dp"
android:focusableInTouchMode="true"
app:passwordToggleEnabled="true"
>
<EditText
android:id="@+id/et_confirmPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Confirm Password"
android:ems="10"
android:inputType="textPassword"
android:textSize="22sp"
/>
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/Register_Btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
android:textSize="22sp"
android:layout_marginTop="40dp"
android:background="@drawable/btnbg"
android:textColor="#fff"/>
</LinearLayout>
Create Profile Activity.
activity_profile.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProfileActivity">
<TextView
android:id="@+id/Tv_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile Activity"
android:textSize="40sp"
android:layout_centerInParent="true"/>
<Button
android:id="@+id/LogOut_Btn"
android:layout_width="160dp"
android:layout_height="60dp"
android:text="LogOut"
android:textAllCaps="false"
android:layout_below="@+id/Tv_Text"
android:layout_centerHorizontal="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/LogOut_Btn"
android:layout_centerHorizontal="true"
android:id="@+id/signoutProgressBar"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Signing Out..."
android:textSize="20sp"
android:textColor="#000"
android:layout_alignBottom="@id/signoutProgressBar"
android:layout_alignRight="@id/signoutProgressBar"
android:id="@+id/textSignout"
/>
</RelativeLayout>
Now Write some java code for functionality.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button mRegisterBtn, mLoginBtn;
private EditText mEmail, mPassword;
private ProgressBar mProgressBar;
private TextView mPleaseWait;
private Context mcontext;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAurhListner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRegisterBtn = findViewById(R.id.Register_Here);
mLoginBtn = findViewById(R.id.Btn_Login);
mEmail = findViewById(R.id.UserEmail);
mPassword = findViewById(R.id.UserPassword);
mProgressBar = findViewById(R.id.ProgressBarr);
mPleaseWait = findViewById(R.id.TV_PleaseWait);
mcontext = MainActivity.this;
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
setUPFirebaseAuth();
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intet = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intet);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(MainActivity.this, "Please Enter Username", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(MainActivity.this, "Please Enter Username", Toast.LENGTH_SHORT).show();
return;
}
mProgressBar.setVisibility(View.VISIBLE);
mPleaseWait.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
try{
FirebaseUser user = mAuth.getCurrentUser();
if (user.isEmailVerified()){
Log.e(TAG, "onComplete: Email Verified ");
Toast.makeText(mcontext, "Login Sucessfully", Toast.LENGTH_SHORT).show();
Intent intento = new Intent(MainActivity.this, ProfileActivity.class );
startActivity(intento);
}else {
Toast.makeText(mcontext, "Email Not Verified\n Check your Email Inbox", Toast.LENGTH_SHORT).show();
}
} catch (NullPointerException e){
Log.e(TAG, "onComplete: NullPointerException " + e.getMessage() );
}
/* FirebaseUser user = mAuth.getCurrentUser();*/
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
});
if (mAuth.getCurrentUser() !=null){
Intent intento = new Intent(MainActivity.this, ProfileActivity.class );
startActivity(intento);
}
}
private void setUPFirebaseAuth() {
mAuth = FirebaseAuth.getInstance();
mAurhListner = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged: signed in " + user.getUid());
} else {
Log.d(TAG, "onAuthStateChanged: signed out");
}
}
};
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mAuth.addAuthStateListener(mAurhListner);
}
@Override
protected void onStop() {
super.onStop();
if (mAurhListner !=null){
mAuth.removeAuthStateListener(mAurhListner);
}
}
}
Create New Java Class Named FirebaseMethods the name will be anything.
public class FirebaseMethods {
private static final String TAG="FirebaseMethods";
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAurhListner;
private String userID;
private Context mContext;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseRefrence;
public FirebaseMethods(Context context){
mAuth = FirebaseAuth.getInstance();
mContext = context;
if (mAuth.getCurrentUser() != null){
userID = mAuth.getCurrentUser().getUid();
}
}
public void RegisterNewUser(String fullname, String email, String password, String confirmpass){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendVerificationEmail();
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(mContext, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void sendVerificationEmail(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user !=null){
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(mContext, "Check Your Email Inbox\n And Confirm your password", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(mContext, "could not send verification email", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Create Register Activity.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private static final String TAG="RegisterActivity";
private EditText mFullName, mEmail, mPassword, mConfirmPass;
private Button mRegister_Btn;
private Context mContext;
//Firebase
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAurhListner;
FirebaseDatabase mFirebaseDatabase;
DatabaseReference mDatabaseRefrence;
FirebaseMethods firebaseMethods;
private String append = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mContext = RegisterActivity.this;
firebaseMethods = new FirebaseMethods(mContext);
mFullName = findViewById(R.id.et_FullName);
mEmail = findViewById(R.id.et_Email);
mPassword = findViewById(R.id.et_Password);
mConfirmPass = findViewById(R.id.et_confirmPass);
mRegister_Btn = findViewById(R.id.Register_Btn);
Init();
}
public void Init(){
mRegister_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String fullname = mFullName.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
String confirmpass = mConfirmPass.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(mContext, "Please Enter Your Email", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(mContext, "Please Enter Your Password", Toast.LENGTH_SHORT).show();
if (password.length() < 6) {
Toast.makeText(mContext, "Password Should be 6 Characters", Toast.LENGTH_SHORT).show();
}
return;
}
if (TextUtils.isEmpty(confirmpass)) {
Toast.makeText(mContext, "Please ConfirmYour Password", Toast.LENGTH_SHORT).show();
if (!password.equals(confirmpass)) {
Toast.makeText(mContext, "Match Doen't Match", Toast.LENGTH_SHORT).show();
}
return;
}
firebaseMethods.RegisterNewUser(fullname, email, password, confirmpass);
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
finish();
}
});
}
}
Create Profile Activity
ProfileActivity.java
public class ProfileActivity extends AppCompatActivity {
private static final String TAG = "ProfileActivity";
private Button mLogOut;
private ProgressBar mProgressbar;
private TextView tvsignout;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mLogOut = findViewById(R.id.LogOut_Btn);
tvsignout = findViewById(R.id.textSignout);
mProgressbar = findViewById(R.id.signoutProgressBar);
mProgressbar.setVisibility(View.GONE);
tvsignout.setVisibility(View.GONE);
setUPFirebaseAuth();
mLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
startActivity(intent);
mProgressbar.setVisibility(View.VISIBLE);
tvsignout.setVisibility(View.VISIBLE);
mAuth.signOut();
}
});
}
private void setUPFirebaseAuth() {
mAuth = FirebaseAuth.getInstance();
mAuthListner = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged: signed in " + user.getUid());
} else {
Log.d(TAG, "onAuthStateChanged: signed out");
}
}
};
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mAuth.addAuthStateListener(mAuthListner);
}
@Override
protected void onStop() {
super.onStop();
if (mAuthListner !=null){
mAuth.removeAuthStateListener(mAuthListner);
}
}
}
0 Comments