SignIn in Firebase using Email and Google Account (Java)
This is main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="108dp"
android:ems="10"
android:hint="Email"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:ems="10"
android:hint="password"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPassword" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:text="register"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.888"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="google sign in"
app:layout_constraintBottom_toTopOf="@+id/button2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is Registerpage
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".registerPage">
<EditText
android:id="@+id/editTextTextPersonName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="208dp"
android:ems="10"
android:hint="Email"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextTextPassword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="password"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPassword2" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.919"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button3"
app:layout_constraintVertical_bias="0.904" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is Dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/emailFromFirebase"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DashboardPage">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Dashboard."
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/signOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sign out"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.337" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.614" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is MainActivity
package com.example.firebasewithemail;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.firebasewithemail.Models.ViewModel;
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.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
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;
public class MainActivity extends AppCompatActivity {
private Button loginBtn;
private Button registerBtn;
private Button googleSignIn;
private EditText emailFeild;
private EditText passFeild;
private FirebaseAuth auth = FirebaseAuth.getInstance();
private ViewModel viewModel;
private GoogleSignInClient googleSignClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginBtn = findViewById(R.id.button);
registerBtn = findViewById(R.id.button2);
emailFeild = findViewById(R.id.editTextTextPersonName);
passFeild = findViewById(R.id.editTextTextPassword);
googleSignIn = findViewById(R.id.button5);
viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(ViewModel.class);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = emailFeild.getText().toString();
String pass = passFeild.getText().toString();
if (email.isEmpty() && pass.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please enter your email and password", Toast.LENGTH_SHORT).show();
} else {
viewModel.signInWithEmail(email, pass);
viewModel.user.observe(MainActivity.this, new Observer<FirebaseUser>() {
@Override
public void onChanged(FirebaseUser firebaseUser) {
if (firebaseUser != null) {
startActivity(new Intent(MainActivity.this, DashboardPage.class));
} else {
Toast.makeText(MainActivity.this, "These Credential is not match with our database.", Toast.LENGTH_LONG)
.show();
}
}
});
}
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, registerPage.class));
}
});
googleSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleSignClient = GoogleSignIn.getClient(MainActivity.this, gso);
Intent intent = googleSignClient.getSignInIntent();
launcher.launch(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
if (FirebaseAuth.getInstance().getCurrentUser() != null){
startActivity(new Intent(MainActivity.this, DashboardPage.class));
}
}
ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), (ActivityResult result) -> {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(result.getData());
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
viewModel.signWithGoogle(MainActivity.this, account.getIdToken());
} catch (ApiException e) {
Log.w("TAG", "Google sign in failed", e);
}
});
}
This is RegisterActivity
package com.example.firebasewithemail;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.firebasewithemail.Models.ViewModel;
import com.google.firebase.auth.FirebaseUser;
public class registerPage extends AppCompatActivity {
private Button registerBtn;
private Button loginBtn;
private EditText emailFeild;
private EditText passFeild;
private ViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_page);
loginBtn = findViewById(R.id.button4);
registerBtn = findViewById(R.id.button3);
emailFeild = findViewById(R.id.editTextTextPersonName2);
passFeild = findViewById(R.id.editTextTextPassword2);
viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(ViewModel.class);
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = emailFeild.getText().toString();
String pass = passFeild.getText().toString();
if (email.isEmpty() && pass.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please enter your email and password", Toast.LENGTH_SHORT).show();
} else {
viewModel.signUpWithEmail(registerPage.this, email, pass);
}
}
});
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
This is DashboardActivity
package com.example.firebasewithemail;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.firebasewithemail.Models.ViewModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class DashboardPage extends AppCompatActivity {
private final FirebaseAuth auth = FirebaseAuth.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard_page);
TextView showEmail = findViewById(R.id.textView2);
String email = auth.getCurrentUser().getEmail();
showEmail.setText(email);
Toast.makeText(getApplicationContext(), "You Successfully log in.", Toast
.LENGTH_LONG)
.show();
Button signOut = findViewById(R.id.signOut);
signOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auth.signOut();
finish();
}
});
}
}
This is Repository class
package com.example.firebasewithemail.Models;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import com.example.firebasewithemail.DashboardPage;
import com.example.firebasewithemail.R;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
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.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class FireRepo {
private FirebaseAuth auth = FirebaseAuth.getInstance();
private FirebaseFirestore db = FirebaseFirestore.getInstance();
MutableLiveData<FirebaseUser> signUpWithEmail(String email, String pass) {
MutableLiveData<FirebaseUser> user = new MutableLiveData<>();
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
user.setValue(auth.getCurrentUser());
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
return user;
}
void signUpWithEmail(Context context, String email, String pass) {
auth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
addingUserToFirebase(task.getResult().getUser().getEmail());
Toast.makeText(context, "You successfully register.", Toast.LENGTH_LONG)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(context, "Something Went Wrong.", Toast.LENGTH_LONG)
.show();
}
});
}
void signInWithGoogle(Context context, String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
addingUserToFirebase(task.getResult().getUser().getEmail());
context.startActivity(new Intent(context, DashboardPage.class));
}
});
}
void addingUserToFirebase(String email) {
Map<String, String> data = new HashMap<>();
data.put("Email", email);
db.collection("Users")
.add(data);
}
}
This is ViewModel
package com.example.firebasewithemail.Models;
import android.app.Application;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.firebase.auth.FirebaseUser;
public class ViewModel extends AndroidViewModel {
public MutableLiveData<FirebaseUser> user;
FireRepo repository = new FireRepo();
public ViewModel(Application application) {
super(application);
}
public void signInWithEmail(String email, String pass) {
user = repository.signUpWithEmail(email, pass);
}
public void signUpWithEmail(Context context, String email, String pass) {
repository.signUpWithEmail(context, email, pass);
}
public void signWithGoogle(Context context, String idToken) {
repository.signInWithGoogle(context, idToken);
}
}
This simple app is for signing in firbase using email, password and Google singIn method both.
SignIn in Firebase using Email and Google Account (Java)
Reviewed by Coding Arc
on
June 28, 2021
Rating:
No comments: