Making decision based on retrieved Data from Firebase - Android [duplicate] - java

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();
}
}

Related

How to check for new user when log in with google authentication?

I want to know if user is new or exists . I want to show additional View if user is new.
I have implemented google sign in using this link https://developers.google.com/identity/sign-in/android/sign-in
. Everything is working fine but addition i want to know if user is new or not.
if log in user is new i want to do some Stuffs.
Here is my code for login using Google Authenticaion.
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
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.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;
import java.util.ArrayList;
import java.util.Objects;
public class Login extends AppCompatActivity {
private static final int RC_SIGN_IN = 100;
LinearLayout button;
GoogleSignInClient mGoogleSignInClient;
GoogleSignInAccount account;
DatabaseReference databaseReference;
ProgressDialog progressDialog;
long childTotal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
button = findViewById(R.id.loginBtn);
getWindow().setStatusBarColor(getResources().getColor(R.color.white));
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(Login.this, gso);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
childTotal = snapshot.getChildrenCount();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressDialog = new ProgressDialog(Login.this);
progressDialog.setMessage("Please wait . . . ");
progressDialog.setCancelable(false);
progressDialog.show();
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
if (account!=null){
addUserDataToDatabase();
startActivity(new Intent(Login.this, MainActivity.class));
progressDialog.dismiss();
finish();
}
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
progressDialog.dismiss();
// Toast.makeText(this, "Request cancelled by user.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
account = GoogleSignIn.getLastSignedInAccount(this);
if (account!=null) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
private void addUserDataToDatabase(){
UserModel userModel = new UserModel();
userModel.setName(account.getDisplayName());
userModel.setEmail(account.getEmail());
if (account.getPhotoUrl()==null){
userModel.setPicture("No image available");
}else {
userModel.setPicture(String.valueOf(account.getPhotoUrl()));
}
databaseReference.child(Objects.requireNonNull(account.getDisplayName()))
.setValue(userModel);
}
}
If you want to check if the user is new in Firebase, then you can use my answer from the following post:
How to check if user is new using GoogleSignInOptions in android studio using java?
If you don't want to use Firebase authentication, but I highly recommend you implement it, then you can add the user object in Firestore or in the Realtime Database.
Since you're using Java, for checking a user for existence in Firestore, please check the following answer:
Firestore query - checking if username already exists
And for checking a user for existence in the Realtime Database, then please check the following answer:
Checking if a particular value exists in the Firebase database
So when a user creates a new account, first check if the UID already exists in the database. If it doesn't, then the user is new, otherwise is an existing user.

Invalid GmsCore APK, remote loading disabledrequires the Google Play Store but it is missing Firebase object access showing null pointer exception

I am writing a sign-in page but the problem here is that every time I click on signin button it doesn't show my homepage but the words "please waiting" keep showing up. I am a newbie to java and firebase, I also searched a lot of websites but didn't find a solution. Does anyone, please help me?
Realtime database :
here is code
package com.example.eatit_new;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import com.example.eatit_new.Common.Common;
import com.example.eatit_new.Model.User;
import com.google.android.material.snackbar.Snackbar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.eatit_new.databinding.ActivitySignInBinding;
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;
import com.rengwuxian.materialedittext.MaterialEditText;
public class SignIn extends AppCompatActivity {
EditText editPhone, editPassword;
Button btnSignIn;
#Override
protected void onCreate (Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_sign_in);
editPassword=(MaterialEditText)findViewById(R.id.editPassword);
editPhone= (MaterialEditText)findViewById(R.id.editPhone);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
//init Database
final FirebaseDatabase database= FirebaseDatabase.getInstance();
final DatabaseReference table_user=database.getReference("User");
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog mDialog = new ProgressDialog(SignIn.this);
mDialog.setMessage("Please waiting....");
mDialog.show();
table_user.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Check if user not exist in database
if (dataSnapshot.child(editPhone.getText().toString()).exists()) {
//Get User Information
mDialog.dismiss();
User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
if (user.getPassword().equals(editPassword.getText().toString())) {
Intent homeIntent= new Intent(SignIn.this,Home.class);
Common.currentUser= user;
startActivity(homeIntent);
finish();
} else {
Toast.makeText(SignIn.this, "Wrong password!", Toast.LENGTH_SHORT).show();
}
} else {
mDialog.dismiss();
Toast.makeText(SignIn.this, "User not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
}
in User class :
package com.example.eatit_new.Model;
public class User {
String name;
String password;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
}
and I am getting "nullpointerException"
When you create a reference that points to the User node and when you attach a listener to it:
DatabaseReference table_user=database.getReference("User");
It means that you reading (downloading) all the data beneath that node. This is considered an antipattern, since downloading the entire node of users is definitely a waste of resources and bandwidth. If you want to check some data against a specific user, then you should consider adding the typed phone number to the reference. This means that you'll always read a single user, rather than all users. Assuming that the user types in the editPhone EditText one of the numbers that exist in your screenshot, the code should look like this:
String phone = editPhone.getText().toString().trim();
String password = editPassword.getText().toString();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference phoneRef = db.child("User").child(phone);
phoneRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
User user = snapshot.getValue(User.class);
if(user.getPassword().equals(password)) {
//Go to next activity
} else {
Toast.makeText(SignIn.this, "Wrong password!", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});

Password length through Firebase authentication

How do I make an error message on password length? through Firebase Authentication for login. If final EditText mpassword.mpassword.setError("Password Must be Between 8 and 15 Characters.");
return;
I have tried to make an if/else statement out of the password length, but that didn't even seem to work right.
Here is the code I have so far.
package com.debatewithus.ui.login;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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.debatewithus.MainActivity;
import com.debatewithus.R;
import com.debatewithus.User;
import com.debatewithus.UserLocalStore;
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 static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
public class LoginActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState, ClassNotFoundException task) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
Button login;
Button sign_up;
final EditText mail;
final EditText mpassword;
TextView forgotpassword;
final FirebaseAuth auth;
auth = FirebaseAuth.getInstance();
mail = findViewById(R.id.username);
mpassword = findViewById(R.id.Password);
login = findViewById(R.id.login);
sign_up = findViewById(R.id.signup);
forgotpassword = findViewById(R.id.forgotpassword);
login.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}));
sign_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_address = mail.getText().toString().trim();
String password = mpassword.getText().toString().trim();
if (TextUtils.isEmpty(email_address)) {
mail.setError("Email is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
mpassword.setError("Password Required.");
return;
if (!(password.length() < 8 && (password.length() > 15))) {
final EditText mpassword.mpassword.setError("Password Must be Between 8 and 15 Characters.");
return;
}
auth.signInWithEmailAndPassword(email_address, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
startActivity(new Intent(getApplicationContext(), MainActivity.class) {
});
else {
Toast.makeText(LoginActivity.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
};
});
};
};
});
};
};
You need a logical OR with || instead of a logical AND with &&:
if (!(password.length() < 8 || (password.length() > 15)))
This will evaluate to true if the password length if less than 8 OR greater than 15.
Replace AND with OR , then remove ! . That should do it.
if ((password.length() < 8 || (password.length() > 15))) {

Firebase registered with email and pass - how add additional details to the users [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I know this has been discussed plenty of times, unfortunately I am a noob and didn`t find the answers useful enough.
Basically, my app registers the users to Firebase using the email and pass registration method. I also need another 2 fields for the users, name and lastname. I understand these have to be saved in
the Realtime Database.
This is my code:
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
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;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.FirebaseDatabase;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText editTextEmail;
EditText editTextPassword;
EditText editTextRePassword;
EditText editTextName;
EditText editTextLastName;
Button buttonSignup;
TextView textViewSignin;
ProgressDialog progressDialog;
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);
editTextRePassword = (EditText) findViewById(R.id.editTextRePassword);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextLastName = (EditText) findViewById(R.id.editTextLastName);
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 boolean isValidEmail(String email){
boolean isValidEmail = false;
String regExpn = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (email.matches(regExpn))
{
isValidEmail = true;
}
return isValidEmail;
}
private void registerUser(){
//getting email and password from edit texts
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
String repass = editTextRePassword.getText().toString().trim();
String name = editTextName.getText().toString().trim();
String lastname = editTextLastName.getText().toString().trim();
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"Please enter the password",Toast.LENGTH_LONG).show();
return;
}
else if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show() ;
return;
}
else if (TextUtils.isEmpty(repass)){
Toast.makeText(this,"Please repeat the password",Toast.LENGTH_LONG).show();
return;
}
else if (!password.equals(repass)) {
Toast.makeText(this,"You must input the same password as in the previous field",Toast.LENGTH_LONG).show();
return;
}
else if(!isValidEmail(email.toString().trim()))
{
Toast.makeText(this,"Please use a valid email address",Toast.LENGTH_LONG).show();
return;
}
else if (password.length()<6) {
Toast.makeText(this,"Your password must be at least 6 characters long",Toast.LENGTH_LONG).show();
return;
}
else if(TextUtils.isEmpty(name)){
Toast.makeText(MainActivity.this, "Please enter your name", Toast.LENGTH_LONG).show() ;
return;
}
else if (TextUtils.isEmpty(lastname)){
Toast.makeText(this,"Please input your last name",Toast.LENGTH_LONG).show();
return;
}
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()){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
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));
}
}
}
Any help appreciated.
See this Answer: https://stackoverflow.com/a/39077132/7160752
You would have to create a users child in your database that contains all the extra user information. The way I do this is after a user successfully signs up, you can store their info under users/:userId
#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");
User user = new User(name, email, phoneNumber);
FirebaseDatabase.getInstance().getReference().child("users").child(mAuth.getCurrentUser()).setValue(user);
updateUI(user);
} else {
}
}
});

Unable to successfully complete authentication

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.

Categories

Resources