problem in create user in Firebase in android - android

i wrote these two functions and called theme in signup button but no user is created in Firebase.(The connection between the app and Firebase is done correctly) so whats the problem?
private void attemptRegistration() {
// Reset errors displayed in the form.
edtEmail.setError(null);
edtPassword.setError(null);
// Store values at the time of the login attempt.
String email = edtEmail.getText().toString();
String password = edtPassword.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
edtPassword.setError(getString(R.string.error_invalid_password));
focusView = edtPassword;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
edtEmail.setError(getString(R.string.error_field_required));
focusView = edtEmail;
cancel = true;
} else if (!isEmailValid(email)) {
edtEmail.setError(getString(R.string.error_invalid_email));
focusView = edtEmail;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// TODO: Call create FirebaseUser() here
createFirebaseUser();
}
}
private void createFirebaseUser() {
String email = edtEmail.getText().toString();
String password = edtPassword.getText().toString();
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this,
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("FlashChat", "createUser onComplete: " + task.isSuccessful());
if (!task.isSuccessful()) {
Log.d("FlashChat", "user creation failed");
showErrorDialog("Registration attempt failed");
} else {
saveDisplayName();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
finish();
startActivity(intent);
}
}
});
}

Related

Identify two users with the same email address

I'm currently working on a parental control application, what I would want to achieve is that the parent and child can login to the system with the same email address on different devices, and I also want to achieve auto login feature, when the parent open the app, it will directly load the ParentActivity, if child then load the ChildActivity.
But now the problem is that I can't do this, I have no idea how to identify both of them since they are using the same email address. Previously, I was able to perform auto login for the parent by using FirebaseAuth.getCurrentUser(), and then check the userType inside firestore. But now I can't check anything to identify whether the user is a child or parent.
What I have tried:
Create a field call "child", when the user (John) login as child, update the field with "TRUE" (let's say), when John quit app and login again, the system will starting checking if userType == "parents", if no then only it will check if child == "TRUE". Therefore, the child user will always be auto login to the ParentActivity but ChildActivity.
Is there any way to achieve this? Hope you guys understand what my problem is. The attached image shows how I achieve auto login for parent previously. Thanks in advance!
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Transparent Status Bar
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
ButterKnife.bind(this);
//FirebaseApp.initializeApp(this.getBaseContext());
firebaseAuth = FirebaseAuth.getInstance();
clearUserType();
}
// Hide keyboard after user clicking somewhere
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#OnClick(R.id.LoginButton)
public void login(){
progressBar.setVisibility(View.VISIBLE);
if (!Utils.isValidEmail(email, emailLayout) | !Utils.hasEmail(email, emailLayout) | !Utils.hasPassword(password, passwordLayout)){
progressBar.setVisibility(View.INVISIBLE);
return;
}
startSignIn(email.getText().toString(), password.getText().toString());
}
#OnClick(R.id.SignUpButton)
public void signUpScreen(){
Intent signup = new Intent(this, SignUpActivity.class);
startActivity(signup);
finish();
}
#OnTextChanged(value = R.id.LoginEmailText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
public void emailChanged(CharSequence s){
if(!(s.length() < 1)){
emailLayout.setError(null);
}
}
#OnTextChanged(value = R.id.LoginPasswordText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
public void passwordChanged(CharSequence s){
if(!(s.length() < 1)){
passwordLayout.setError(null);
}
}
private void startSignIn(String email, String password){
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(task -> {
try {
if (task.isSuccessful()) {
updateUI();
}
else {
String error = task.getException().getMessage();
if (error.contains("There is no user record corresponding to this identifier. The user may have been deleted.") ||
error.contains("The password is invalid or the user does not have a password."))
{
Utils.ErrorSweetDialog(LoginActivity.this, "Login Failed", "Incorrect email or pasword. Please try again.",
"OK");
}
else if (error.contains("A network error (such as timeout, interrupted connection or unreachable host) has occurred.")){
Utils.ErrorSweetDialog(LoginActivity.this, "No Internet Connection",
"Please check your internet connection and try again.", "OK");
}
else
{
Utils.ErrorSweetDialog(LoginActivity.this, "Login Failed", error, "OK");
}
}
progressBar.setVisibility(View.INVISIBLE);
}
catch (Exception e){
Utils.ErrorSweetDialog(LoginActivity.this, "Oops! Something went wrong.",
"Sorry for the inconvenience. Please try again later.", "OK");
}
});
}
#Override
protected void onStart() {
super.onStart();
//clearUserType();
//FirebaseUser user = firebaseAuth.getCurrentUser();
/*DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
}
}
else{
}
}
});*/
/*if(user != null){
//updateUI();
String uid = firebaseAuth.getCurrentUser().getUid();
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
if (userType.contains("parents")){
Log.e("contain parents", "yes");
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else{
}
}
}
else{
}
}
});
Intent intent = new Intent(this, ParentActivity.class);
startActivity(intent);
finish();
}
else{
Log.e("Login", "hi");
}*/
}
private void updateUI(){
Intent intent = new Intent(this, PickRoleActivity.class);
startActivity(intent);
finish();
}
private void clearUserType(){
FirebaseUser user = firebaseAuth.getCurrentUser();
//Log.e("urrent user", user.toString());
if(user != null){
progressBar.setVisibility(View.VISIBLE);
Log.e("user null: ", "no");
//updateUI();
String uid = firebaseAuth.getCurrentUser().getUid();
Log.e("UID: ",uid);
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
String childStatus = document.getString("child");
Log.e("LoginActivity",userType);
if (userType.contains("parents")){
Log.e("contain parents", "yes");
progressBar.setVisibility(View.INVISIBLE);
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else if (childStatus.contains("TRUE")){
progressBar.setVisibility(View.INVISIBLE);
}
}
}
else{
Log.e("task unsuccessful:", " yes");
}
}
});
}
else{
Log.e("NULL: ", "No Such User.");
}
}
}
User account data in firestore
I assume you are enabling creation of multiple accounts with the same email address, which means the parent and the child have different passwords. With that, I suggest you take a look at Custom Claims. It basically give an account a 'tag' that you can access client side. Please notice that this will require you to write some Cloud Functions when creating accounts
EDIT: It's seem that you need a SharedPreferences. Here are the docs : developer.android.com/training/data-storage/shared-preferences . This way you can store a key like isParent:true in a SharedPreferences, and read its value everytime the app is started instead of saving it to Firestore.
You can check them at onCreate for Login Activity or if you have Splash Activity, you can check there.
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
if (userType.equal("parents")){
Log.e("contain parents", "yes");
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else if (userType.equal("child")) {
//Here you missed, when child login
}
}
}
}
});

Firebase authentication keeps giving a com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference

I am trying to implement Firebase authentication for an android app and I keep getting an error. I am new to Android and at best a Java novice so I am sure it is something simple that I am missing. Any suggestions/advice is much appreciated!
Here is my code base:
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
//Firebase
private FirebaseAuth mAuth;
private Context mContext;
private ProgressBar mProgressBar;
private EditText mEmail, mPassword;
private TextView mPleaseWait;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mPleaseWait = (TextView) findViewById(R.id.pleaseWait);
mEmail = (EditText)findViewById(R.id.input_email);
mPassword = (EditText) findViewById(R.id.input_password);
mContext = LoginActivity.this;
Log.d(TAG, "onCreate: Login started.");
mPleaseWait.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
}
private boolean isStringNull(String string){
Log.d(TAG, "isStringNull: checking if null.");
if(string.equals("")){
return true;
}else {
return false;
}
}
/**
* FireBase Code
*
*/
private void init(){
//initialize the button for logging in
Button btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: attempting to login. ");
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(mContext, "You must fill out all fields.", Toast.LENGTH_SHORT).show();
}else{
mProgressBar.setVisibility(View.VISIBLE);
mPleaseWait.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.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");
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
}
});
}
/**
* Checks to see if the #param 'user' is logged in.
*/
private void updateUI(FirebaseUser currentUser) {
Log.d(TAG, "updateUI: checking if user is logged in.");
if(currentUser == null){
Intent intent = new Intent(mContext, LoginActivity.class);
startActivity(intent);
}
}
#Override
public void onStart() {
Log.d(TAG, "onStart: Starting LoginActivity onStart method.");
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
if(currentUser != null){
Log.d(TAG, "onStart:signed_in. " + currentUser);
}else{
Log.d(TAG, "onStart:signed_out. ");
}
}
}
When I run the code I get the following error message:
D/LoginActivity: onCreate: Login started.
onStart: Starting LoginActivity onStart method. D/AndroidRuntime: Shutting down VM .......java.lang.NullPointerException: Attempt to
invoke virtual method 'com.google.firebase.auth.FirebaseUser
com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null
object reference
The error message is suggesting that mAuth is null, its default value. You likely never assigned it a value.

how to hash Password and store in firebase

I have been trying to make a registration page. I'm using email authentication. My registered data is stored in a firebase database.
For security purposes, I want my password string to be hidden. So for that I'm using SHA-256 to hash but it's not working.
Here is my code:
protected void setUpUser() {
user = new User();
user.setName(name.getText().toString().trim());
user.setPhoneNumber(phoneNumber.getText().toString().trim());
user.setAddress(address.getText().toString().trim());
user.setEmail(email.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
}
#Override
public void onClick(View v) {
String pass = password.getText().toString();
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] hash = digest.digest(pass.getBytes(StandardCharsets.UTF_8));
mref = new Firebase("https://tango-3a561.firebaseio.com/");
createNewAccount(email.getText().toString(), hash);
}
private void createNewAccount(String email, final byte[] password) {
Log.d(TAG, "createNewAccount:" + email);
if (!validateForm()) {
return;
}
//This method sets up a new User by fetching the user entered details.
setUpUser();
//This method method takes in an email address and password, validates them and then creates a new user
// with the createUserWithEmailAndPassword method.
// If the new account was created, the user is also signed in, and the AuthStateListener runs the onAuthStateChanged callback.
// In the callback, you can use the getCurrentUser method to get the user's account data.
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, String.valueOf(password))
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "Register Successfully " + task.isSuccessful());
hideProgressDialog();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
/* Toast.makeText(RegisterActivity.this, "Registration failed.", Toast.LENGTH_SHORT).show();
hideProgressDialog();*/
if (task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(RegisterActivity.this,"User with this email already exist.",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
/* if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "minimum password!", Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
Toast.makeText(getApplicationContext(), "Registration failed.!", Toast.LENGTH_SHORT).show();
hideProgressDialog();
}*/
} else {
onAuthenticationSuccess(task.getResult().getUser());
Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
} hideProgressDialog();
}
});
}
private void onAuthenticationSuccess(FirebaseUser mUser) {
// Write new user
saveNewUser(mUser.getUid(), user.getName(), user.getPhoneNumber(),user.getAddress(), user.getEmail(), user.getPassword());
signOut();
// Go to LoginActivity
Intent i =new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
}
private void saveNewUser(String userId, String name, String phone, String address, String email, String password) {
User user = new User(userId,name,phone,address,email,password);
mref.child("Users").child(name).setValue(user);
}
private void signOut() {
mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
boolean valid = true;
String userName = name.getText().toString();
if (TextUtils.isEmpty(userName)) {
name.setError("Required.");
valid = false;
} else {
name.setError(null);
}
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
if (!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()) {
email.setError("Invalid Mail Address.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
String userPhoneNumber = phoneNumber.getText().toString();
if (TextUtils.isEmpty(userPhoneNumber)){
phoneNumber.setError("Required");
valid = false;
}else {
phoneNumber.setError(null);
}
if (phoneNumber.length() < 10){
phoneNumber.setError("Should be 10 Digit");
valid = false;
}else {
phoneNumber.setError(null);
}
String userAddress = address.getText().toString();
if (TextUtils.isEmpty(userAddress)){
address.setError("Required");
valid = false;
}else {
address.setError(null);
}
/* if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
Toast.makeText(getApplicationContext(),"please enter valid email",Toast.LENGTH_LONG).show();
}*/
/* if (Patterns.PHONE.matcher(userPhoneNumber).matches()){
Toast.makeText(getApplicationContext(),"please enter valid mobile no",Toast.LENGTH_LONG).show();
}*/
if (userName.isEmpty() && userEmail.isEmpty() && userPassword.isEmpty() && userAddress.isEmpty() && userPhoneNumber.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are mandatory",Toast.LENGTH_LONG).show();
}
return valid;
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
As you can see my password is not hashed.
I have solved this type of issue with this code:
public static String sha256(String base) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
Then you just call the method and pass the password field:
String newPass = sha256(pass).toString();
Edit
At your question, this would solve the problem:
#Override
public void onClick(View v) {
String pass = password.getText().toString();
String newPass = sha256(pass);
mref = new Firebase("https://tango-3a561.firebaseio.com/");
createNewAccount(email.getText().toString(), newPass );
}
Change your method params:
private void createNewAccount(String email,String pass)....

Firebase: onComplete() in createUserWithEmailAndPassword is never run,,

good Day
I'm trying to sign up a new account using firebase,but onComplete method it's never run I tried to check if there is any error by break point but it's never reached to it..as well I tried to make sure the password not less than 6 char,and email/password verification is enabled in firebase console..
here is my code
public class CreateAccountActivity extends AppCompatActivity {
private EditText emailedittxt;
private EditText passwordedittext;
private Button signUp;
//private EditText nametext;
private static final String TAG = "EmailPassword";
//Authentication
private FirebaseAuth mAuth;
// public static Intent newIntent(Context packageContext){
// Intent intent = new Intent(packageContext,CreateAccountActivity.class);
// return intent;
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
mAuth = FirebaseAuth.getInstance();
// nametext = (EditText) findViewById(R.id.RnameText);
emailedittxt = (EditText) findViewById(R.id.RemailText);
passwordedittext = (EditText) findViewById(R.id.RpasswordText);
signUp = (Button) findViewById(R.id.RsignupButton);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// signUp();
//create new Account
// String name = nametext.getText().toString();
String email = emailedittxt.getText().toString();
String password = passwordedittext.getText().toString();
//validate the felids
// if (TextUtils.isEmpty(name)) {
// Toast.makeText(CreateAccountActivity.this, "Enter your nmae", Toast.LENGTH_SHORT).show();
// return;
// }
if (TextUtils.isEmpty(email)) {
Toast.makeText(CreateAccountActivity.this, "Enter your email", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(CreateAccountActivity.this, "Enter your password", Toast.LENGTH_SHORT).show();
return;
}
/*Create
new account */
SignUp(email,password);
}
});
}
private void SignUp(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateAccountActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// // Toast.makeText(CreateAccountActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// // signed in user can be handled in the listener.
if (task.isSuccessful()) {
Intent intent = new Intent (CreateAccountActivity.this,Main2Activity.class);
startActivity(intent);
// startActivity(new Intent(CreateAccountActivity.this, Main2Activity.class));
finish();
} else {
Log.d(TAG, "onComplete: Failed=" + task.getException().getMessage()); //ADD THIS
//
//// Toast.makeText(CreateAccountActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_SHORT).show();
}}
});
}
}
anyone have any idea why it's never run onComplete()
Try adding onFailureListener() :
private void SignUp(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateAccountActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// // Toast.makeText(CreateAccountActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// // signed in user can be handled in the listener.
if (task.isSuccessful()) {
Intent intent = new Intent (CreateAccountActivity.this,Main2Activity.class);
startActivity(intent);
// startActivity(new Intent(CreateAccountActivity.this, Main2Activity.class));
finish();
} else {
Log.d(TAG, "onComplete: Failed=" + task.getException().getMessage()); //ADD THIS
//
//// Toast.makeText(CreateAccountActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_SHORT).show();
}}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("exception",e.getMessage());
}
});
}

Firebase auth with email and password NPE

In 10% of the cases there is a null pointer exception when trying to log in with the email and password authentication with Firebase. This only happens in the release apk. It doesn't occur in the debug app. It says it can't pass null for email. But the email is filled in. And otherwise Firebase sents an error code, but not a npe.
This is the error message:
Caused by: java.lang.NullPointerException: Can't pass null for argument 'email' in authWithPassword()
at com.firebase.client.Firebase.authWithPassword(Unknown Source)
at com.example.verdienapp.ui.start.StartActivity$LoginTask.doInBackground(Unknown Source)
at com.example.verdienapp.ui.start.StartActivity$LoginTask.doInBackground(Unknown Source)
My apologies. I should have directly added my code.
First validating the input:
private void validate() {
this.mEmailEditText.setError(null);
this.mPasswordEditText.setError(null);
String email = this.mEmailEditText.getText().toString();
String password = this.mPasswordEditText.getText().toString();
boolean cancel = false;
View focusView = null;
if (TextUtils.isEmpty(password)) {
this.mPasswordEditText.setError(getString(R.string.error_field_required));
focusView = this.mPasswordEditText;
cancel = true;
} else if (password.length() < 6) {
this.mPasswordEditText.setError(getString(R.string.error_invalid_password));
focusView = this.mPasswordEditText;
cancel = true;
}
if (TextUtils.isEmpty(email)) {
this.mEmailEditText.setError(getString(R.string.error_field_required));
focusView = this.mEmailEditText;
cancel = true;
} else if (!email.contains("#")) {
this.mEmailEditText.setError(getString(R.string.error_invalid_email));
focusView = this.mEmailEditText;
cancel = true;
}
if (cancel) {
if (focusView != null) {
focusView.requestFocus();
}
} else {
Utils.closeKeyboard(getActivity(), this.mEmailEditText);
LoginEvent event = new LoginEvent(R.id.button_login, email, password);
BusProvider.getInstance().post(event);
}
}
Then the login event:
private void login(final ButtonEvent buttonEvent) {
LoginEvent loginEvent = (LoginEvent) buttonEvent;
new LoginTask().execute();
email = loginEvent.getEmail();
password = loginEvent.getPassword();
}
And finally the login process with Firebase in a AsyncTask.
private class LoginTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(StartActivity.this);
progressDialog.setTitle(“please wait..");
progressDialog.setMessage(“authorizing...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
mFirebase.authWithPassword(email, password, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Intent intent2 = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent2);
finish();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// error encountered
switch (firebaseError.getCode()) {
case FirebaseError.USER_DOES_NOT_EXIST:
// handle a non existing user
Toast.makeText(getApplicationContext(), getString(R.string.error_user_not_exist)
Toast.LENGTH_LONG).show();
break;
case FirebaseError.INVALID_PASSWORD:
// handle an invalid password
Toast.makeText(getApplicationContext(), getString(R.string.error_invalid_password)
Toast.LENGTH_LONG).show();
break;
default:
// handle other errors
Toast.makeText(getApplicationContext(), getString(R.string.error_reset_password),
Toast.LENGTH_LONG).show();
break;
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}

Categories

Resources