In the following code, I am trying to open a Login page. User will fill in email and password. When user clicks on login button, checkLogin method is called.
I understand that in the onComplete method, the 1st if block checking success (filling in email, password and clicking login) is not called. I always get the Toast message "Error login" (the else block).
package com.awani.pocketblog;
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.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;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
private EditText mLoginEmailField;
private EditText mLoginPasswordField;
private Button mLoginButton;
private Button mNewAccountButton;
private FirebaseAuth mAuth;
private ProgressDialog mProgress;
private DatabaseReference mDatabaseUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseUsers.keepSynced(true);
mLoginEmailField = (EditText) findViewById(R.id.loginEmailField);
mLoginPasswordField = (EditText) findViewById(R.id.loginPaswordField);
mLoginButton = (Button) findViewById(R.id.loginButton);
mNewAccountButton = (Button) findViewById(R.id.newAccountButton);
mProgress = new ProgressDialog(this);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkLogin();
}
});
}
private void checkLogin() {
//retrieve the data from database to check if user is logged in correctly
String email = mLoginEmailField.getText().toString().trim();
String password = mLoginPasswordField.getText().toString().trim();
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
mProgress.setMessage("Checking Login...");
mProgress.show();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener < AuthResult > () {
#Override
public void onComplete(#NonNull Task < AuthResult > task) {
//the following if block is never executed....WHY?
if (task.isSuccessful()) {
// Toast.makeText(LoginActivity.this,"hi",Toast.LENGTH_LONG).show();
checkUserExist();
} else {
mProgress.dismiss();
Toast.makeText(LoginActivity.this, "Error Login", Toast.LENGTH_LONG).show();
}
}
});
}
}
private void checkUserExist() {
//retrieving UID
final String user_id = mAuth.getCurrentUser().getUid();
//check if the user with thi UID already exists
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(user_id)) {
Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
} else {
Intent setUpIntent = new Intent(LoginActivity.this, SetUpActivity.class);
setUpIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setUpIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
For authentication with email/password, the user must first be created with createUserWithEmailAndPassword():
Tries to create a new user account with the given email address and
password. If successful, it also signs the user in into the app
This example is provided in Step 4 of the guide for password-based authentication:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(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, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
Go to your firebase console, enable sign-in method: Email/Password or Anonymous
If it does not work, please edit your password, maybe it's too short.
Related
I am trying to create a register activity in android my control goes to registration method but and also I have done validation when I click on signUp it directly goes to the next activity without validating or registering
when I start the application
and come to signup activity it works properly
also, the log messages are printing
but after the register method called nothing is working
Control goes to Register() method after that it does not work
it directly opens the next activity
validations and also firebase create method is not accessible
here is the code I have written
package com.ap.pran;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
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;
import com.google.firebase.database.FirebaseDatabase;
public class SignUp extends AppCompatActivity implements View.OnClickListener {
ProgressBar progressBar;
EditText editTextEmail, editTextPassword, editTextMobileNo, editTextVehicleNo, editTextName;
private static final String TAG = " ANAND MESSAGE";
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
Log.i(TAG, "in onCreate1");
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.passWord);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
editTextMobileNo = (EditText) findViewById(R.id.editTextMobileNo);
editTextVehicleNo = (EditText) findViewById(R.id.editTextVehicleNo);
editTextName = (EditText) findViewById(R.id.editTextName);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.buttonSignUp).setOnClickListener(this);
findViewById(R.id.SignIn).setOnClickListener(this);
}
private void registerUser() {
Log.i(TAG, "In register method");
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email is required !!!");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required !!!");
editTextPassword.requestFocus();
return;
}
if (password.length()<6){
editTextPassword.setError("Password length must be greater than 6");
editTextPassword.requestFocus();
return;
}
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(SignUp.this,"User Registred !!!",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUp.this, "User Registration Failed !!!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSignUp:
Log.i(TAG, "In case 1");
registerUser();
break;
case R.id.SignIn:
startActivity(new Intent(this, MainActivity.class));
Log.i(TAG, "In case 2");
break;
}
}
}
You should remember that if you're using this method for the first time :
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(SignUp.this,"User Registred !!!",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUp.this, "User Registration Failed !!!", Toast.LENGTH_SHORT).show();
}
}
});
it will work perfectly. But on registering any user it automatically signs in the user after completing the registration. So, there is no need to sign in again if registered successfully.
To make the new registration again you must log out the previous registered user in that app.
Note :
I'll also recommend you to use Toast.makeText(SignUp.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); in else statement as follows if registration fails:
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(SignUp.this,"User Registred !!!",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUp.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
It will help to identify the reason of registration failure.
What actually i am doing here, When a user login to their account, Then i am checking that whatever they had verified their email address or not, If not then i am starting the EmailVerificationActivity.
From where when user click on SEND VERIFICATION EMAIL Button an Email Verification code will be sent to user's email address.
after that when user successfully verified their email address, when they click SEND VERIFICATION LINK Button again.
Instead of showing toast message
Toast.makeText(this, "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();,
sending the Email Verification link again.
Why isEmailVerified() returning the false condition.
This is my EmailVerificationActivity
package com.socialcodia.sherewatan;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class EmailVerificationActivity extends AppCompatActivity {
private TextView tvEmailAddress;
private Button btnSendVerificationEmail, btnSignOut;
//Firebase
FirebaseAuth mAuth;
FirebaseUser mUser;
String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verification);
//Init
tvEmailAddress = findViewById(R.id.tvEmailAddress);
btnSendVerificationEmail = findViewById(R.id.btnSendVerificationEmail);
btnSignOut = findViewById(R.id.btnSignOut);
//Firebase Init
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
// get and set email address
email = mUser.getEmail();
tvEmailAddress.setText(email);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
}
});
btnSendVerificationEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isEmailVerified();
}
});
}
private void isEmailVerified()
{
if (mAuth.getCurrentUser()!=null)
{
boolean isEmailVerified = mAuth.getCurrentUser().isEmailVerified();
if (isEmailVerified)
{
Toast.makeText(this, "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();
}
else
{
sendVerificationEmail();
}
}
}
private void sendVerificationEmail()
{
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(EmailVerificationActivity.this, "Email verification link has been sent", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(EmailVerificationActivity.this, "Oops! Failed to send email verification link", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendToLoginWithEmail()
{
Intent intent= new Intent(getApplicationContext(),LoginActivity.class);
intent.putExtra("email",email);
startActivity(intent);
finish();
}
private void signOut()
{
mAuth.signOut();
sendToLoginWithEmail();
}
}
You need to reload current user information. You see the data of the user your have from authentication are old and you need to retrieve the latest. Use the reload() method for that.
How i solved the error.
private void isEmailVerified()
{
mAuth.getCurrentUser().reload().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
if (mAuth.getCurrentUser()!=null)
{
boolean isEmailVerified = mAuth.getCurrentUser().isEmailVerified();
if (isEmailVerified)
{
Toast.makeText(getApplicationContext(), "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();
}
else
{
sendVerificationEmail();
}
}
}
});
}
I used the following line to solve this problem
await FirebaseAuth.instance.currentUser!.reload();
My app uses firebase and it needs to send a verification email to the user after registration before they can login. In my code, the app fails to send the verification email and I found out that the user is always null (while debugging) in line 86/88 of my code. any help would be greaty appreciated.
I've tried retracing my steps back but I couldn't get where i nicked an artery
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.text.TextUtils.isEmpty;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuthSetUp();
//widgets
TextView mSignUp = (TextView) findViewById(R.id.sign_up_txt);
TextView forgotPassword = (TextView) findViewById(R.id.forgot_password_txt);
Button mSignIn = (Button) findViewById(R.id.sign_in_btn);
final EditText mEmailSignIn = (EditText) findViewById(R.id.sign_in_email);
final EditText mPasswordSignIn = (EditText) findViewById(R.id.sign_in_password);
mSignUp.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
}));
//sign in process
mSignIn.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(mEmailSignIn.getText().toString()) && !isEmpty(mPasswordSignIn.getText().toString())) {
//showProgressBar();
FirebaseAuth.getInstance().signInWithEmailAndPassword(mEmailSignIn.getText().toString(), mPasswordSignIn.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//hideProgressBar();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, " Authentication Failed!!!", Toast.LENGTH_LONG).show();
//hideProgressBar();
}
});
} else {
Toast.makeText(LoginActivity.this, "Please, Fill All Fields", Toast.LENGTH_LONG).show();
}
}
}));
}
//Setting up Firebase
private void firebaseAuthSetUp() {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d("TAG", "CurrentUser: " + user);
if (user != null) {
if(user.isEmailVerified()){
Log.d("TAG", "onAuthStateChanged: signed in: " + user.getEmail());
Toast.makeText(LoginActivity.this, "signed in " + user.getUid(), Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginActivity.this, "Please Check Your Email Inbox for Verification Link " + user.getUid(), Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
}
} else {
Toast.makeText(LoginActivity.this, "failed to sign in", Toast.LENGTH_LONG).show();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
}
/*public void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
}
public void hideProgressBar(){
if (mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}*/
}```
Thanks a lot #Praveen and #Alex... figured it out, I made a mistake of signing out the user in the else statement [of the if(user.isEmailVerified()) block in the firebaseAuthSetup() method]. probably wouldn't have gotten it if I didn't retrace from the onComplete()
This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Closed 4 years ago.
Alright so I'm making an online donations portal android application. There will be 2 primary users of the application:
Donors
Charity Organisation Representatives
There is a different UI based on the user type.
Below is the sign up form:
Below is the sign in form:
And the data from the form is added to the database as follows (upon sign up):
Below is the authenticated user's data on firebase:
Below is the sign up class:
package com.example.android.edonate;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
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;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class SignUp extends AppCompatActivity {
//variables to store data from the form
private EditText fname;
private EditText lname;
private EditText email;
private EditText cellNo;
private EditText password;
private Spinner type;
private Button signUp;
//Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mUsersDatabaseReference;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
//Initialize firebase components:
mFirebaseDatabase = FirebaseDatabase.getInstance();
//to set to specific location within the database and storage
mUsersDatabaseReference = mFirebaseDatabase.getReference().child("users");
//Initialize firebase authentication
mAuth = FirebaseAuth.getInstance();
//to get data from the form:
fname=(EditText)findViewById(R.id.fname);
lname=(EditText)findViewById(R.id.lname);
email=(EditText)findViewById(R.id.email);
cellNo=(EditText)findViewById(R.id.mobile_number);
password=(EditText)findViewById(R.id.password);
type=(Spinner)findViewById(R.id.user_category);
signUp = (Button)findViewById(R.id.button_sign_up_2);
//Send button sends a message and clears the EditText
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
User user = new User(fname.getText().toString(), lname.getText().toString(), email.getText().toString(), cellNo.getText().toString(), password.getText().toString(), type.getSelectedItem().toString());
mUsersDatabaseReference.push().setValue(user); //add user details to the database
RegisterUser();
//return to home page after signing up:
//Intent intent = new Intent(SignUp.this,MainActivity.class);
//startActivity(intent);
}
});
}
//to register user to the Firebase 'users'
public void RegisterUser(){
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
if (TextUtils.isEmpty(Email)){
Toast.makeText(this, "Email field is Empty!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(Password)){
Toast.makeText(this, "Password field is Empty!", Toast.LENGTH_SHORT).show();
return;
}
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
try {
//check if successful
if (task.isSuccessful()) {
//User is successfully registered and logged in
//start Profile Activity here
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
Toast.makeText(SignUp.this, "Couldn't register, try again",
Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
WHAT I WANT TO DO is open a different Activity based on whether the signed in user's 'type' (as shown in the database) is donor or charity. Hence the Following steps are needed in the sign in Class:
1. Verify user email and password (that I have already implemented)
2. Get the users record from teh database that has that particular email.
3. Check whether the 'type' field of the selected user record is 'Charity' or 'Donor'
4. Open relevant activity based on the value of type field
Steps 1 and 4 will be implemented easily. Steps 2 and 3 is what I need help with. Steps 2 and 3 will be Implemented in the SigIn.java class. Right now I am opening the DonorHome.java calss by default but I need to add a condition to open either Donor.Home and CHarity.Home
Below is the code for teh SignIn.java class. What is the relevant code I need to add here?:
package com.example.android.edonate;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.util.Log;
import android.net.Uri;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseError;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.Arrays;
import java.util.List;
public class SignIn extends AppCompatActivity {
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mUsersDatabaseReference;
private Button signIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in);
email = (EditText)findViewById(R.id.input_email);
password = (EditText)findViewById(R.id.input_password);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mUsersDatabaseReference = mFirebaseDatabase.getReference();
//.child("users");
signIn = (Button)findViewById(R.id.button_sign_in_2);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v == signIn){
LoginUser();
}
}
});
}
public void LoginUser(){
final String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
mAuth.signInWithEmailAndPassword(Email, Password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
currentUser = mAuth.getCurrentUser();
finish();
startActivity(new Intent(getApplicationContext(),
DonorHome.class));
}else {
Toast.makeText(SignIn.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Starting with tell you that StackOverflow doesn't birth for solution code requests, but for issue or doubts, so ask for many code lines is not so appropriate.
Anyway, you need to do something like this:
public void LoginUser(){
final String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
mAuth.signInWithEmailAndPassword(Email, Password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
currentUser = mAuth.getCurrentUser();
getUserInformation();
//finish(); Don't finish activity now
//startActivity(new Intent(getApplicationContext(),
// DonorHome.class)); Don't start activity without know user type
}else {
Toast.makeText(SignIn.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void getUserInformation(){
//here get User information by firebase querying and get result.....
...onSuccess(){
if(userType.equals("Donor")
startDonorActivityMain();
else
startCharityActivityMain();
}
}
My app runs fine when I test it on an Android device but once the user logs in it crashes instantly and crashes on start up unless I do a clean install of the apk. I'm authenticating users with google sign in with Firebase. The authentication is working fine as users are being registered with my associated Firebase account but I intended for the users to be directed to the Auth activity from my log in activity if they had already logged in but instead I'm experiencing the above issue.
`
package com.test.firebase;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
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;
import android.support.v7.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {
SignInButton button;
FirebaseAuth mAuth;
private final static int RC_SIGN_IN = 2;
GoogleApiClient mGoogleApiClient;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
button = (SignInButton) findViewById(R.id.googleBtn);
mAuth = FirebaseAuth.getInstance();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, Auth.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
private void signIn(){
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()){
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
Toast.makeText(LoginActivity.this, "Auth went wrong", Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("TAG", "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
Log.w("TAG", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
`
I'd appreciate any help I can get with this issue.
Its simple just use this method directly on Onstart it will check if users already exist or not if it does you can simply start other activity.
Just check simply if users are not logged in and somehow you find your self in other activity, just add the else statement to redirect you to first activity!
You Should have pasted the error you got, I can somehow help you more with that in-hand.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});