I am trying to make the EditTextLayout makes an error message when they are empty and the app crashes
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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;
public class LoginActivity extends AppCompatActivity {
private TextInputLayout textInputEmail , textInputPassword;
private Button login;
String emailInput , passwordInput;
private FirebaseAuth auth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
textInputEmail = (TextInputLayout) findViewById(R.id.login_email);
textInputPassword = (TextInputLayout) findViewById(R.id.login_password);
login = (Button)findViewById(R.id.login_button);
progressDialog = new ProgressDialog(this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ConfirmInput();
progressDialog.setTitle("Singing in");
progressDialog.setMessage("Please wait while we sign you in");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
auth.signInWithEmailAndPassword(emailInput , passwordInput).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "Account Created successfuly", Toast.LENGTH_SHORT).show();
SendUserToMainActivity();
}else{
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void SendUserToMainActivity() {
Intent intent = new Intent(LoginActivity.this , MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
public boolean ValidateEmail(){
emailInput = textInputEmail.getEditText().getText().toString().trim();
if(emailInput.isEmpty()){
textInputEmail.setError("You Can't leave this Empty!");
return false;
}else{
textInputEmail.setError(null);
return true;
}
}
public boolean ValidatePassword(){
passwordInput = textInputPassword.getEditText().getText().toString();
if(passwordInput.isEmpty()){
textInputPassword.setError("You Can't leave this Empty!");
return false;
}else{
textInputPassword.setError(null);
return true;
}
}
public void ConfirmInput(){
if(!ValidateEmail() | !ValidatePassword()){
return;
}
}
}
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.zzbq.zzgm(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at com.example.bestever.snapchatclone.LoginActivity$1.onClick(LoginActivity.java:50)
at android.view.View.performClick(View.java:5184)
at android.view.View$PerformClick.run(View.java:20893)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
I tried also to change The TextInputLayout to TextInputEditText and nothing changed. I also tried to change my approach for checking if the TextInputLayout is empty, but it doesn't work
You should validate if textInputEmail.getEditText().getText() is null before retrieving the text from it, that might be the problem. Hope it works.
You can't call getText() function on null String.
Please use this method to implement it in the right way:
String emailInput;
emailInput = textInputEmail.getEditText().getText();
if (emailInput != null) {
emailInput = emailInput.toString().trim();
}
Or (My favorite way)
String emailInput = "";
try {
emailInput = textInputEmail.getEditText().getText().toString().trim();
} catch (IllegalArgumentException ex) { }
Related
Problem
I am trying to make user credentials like username and email to get added in the realtime database. After the user enters their data and hits register button i am getting an error with firebaseMethods.checkIfUsernameExists() method.
Error
FATAL EXCEPTION: main
Process: com.example.movies4u, PID: 25475
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.movies4u.Utils.FirebaseMethods.checkIfUsernameExists(FirebaseMethods.java:47)
at com.example.movies4u.activity_register$1$1.onDataChange(activity_register.java:200)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7081)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
Register Activity Code
package com.example.movies4u;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
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.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.movies4u.Utils.FirebaseMethods;
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.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
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 activity_register extends AppCompatActivity {
TextView HaveAccount;
EditText inputUsername,inputEmail,inputPassword,inputConfirmPassword;
String username,email,password;
Button btnRegister;
FirebaseAuth mAuth;
ProgressBar pb;
private String userID;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseMethods firebaseMethods;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String append;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //Hide status Bar
setContentView(R.layout.activity_register);
firebaseMethods =new FirebaseMethods(activity_register.this);
HaveAccount= (TextView) findViewById(R.id.HaveAccount);
pb = findViewById(R.id.progressBar3);
inputUsername=findViewById(R.id.inputUsername);
inputEmail=findViewById(R.id.inputEmail);
inputPassword=findViewById(R.id.inputPassword);
inputConfirmPassword=findViewById(R.id.inputConfirmPassword);
btnRegister=findViewById(R.id.btnRegister);
username=inputUsername.getText().toString();
email=inputEmail.getText().toString();
password=inputPassword.getText().toString();
pb.setVisibility(View.GONE);
HaveAccount.setOnClickListener(view -> {
Intent loginintent=new Intent(activity_register.this,login_activity.class);
startActivity(loginintent);
});
mAuth=FirebaseAuth.getInstance();
btnRegister.setOnClickListener(view -> ValidateDataandDoRegister());
}
// we will call the method doRegister(username,email,password); in validateDataandDoRegister()
private void doRegister(String username,String email, String password) {
pb.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(task -> {
if(task != null ){
if(mAuth.getCurrentUser() != null){
userID=mAuth.getCurrentUser().getUid();
}
// firebaseMethods.registerNewEmail(username,email,password);
sendVerificationEmail();
// firebaseMethods.addNewUser(email, username);
}
}).addOnFailureListener(e -> {
if(e instanceof FirebaseAuthUserCollisionException){
btnRegister.setEnabled(true);
inputEmail.setError("Email Already Registered");
pb.setVisibility(View.GONE);
inputEmail.requestFocus();
}
else{
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(activity_register.this, "Oops! Something Went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private void sendVerificationEmail() {
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(task -> {
if(task != null && task.isSuccessful()){
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(activity_register.this, "Email has been sent to your email address", Toast.LENGTH_SHORT).show();
//fixing the bug
mAuth.signOut();
}
else {
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Oops! failed to send verification email",Toast.LENGTH_SHORT).show();
}
});
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
//cannot get into this part of code
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user=firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: Make sure the username is not already in use
//Error Occured in the below checkifUsernameExists method call
if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
//to randomly generate key to make sure username is unique
append = myRef.push().getKey().substring(3,10);
Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
}
username = username + append;
//add new user to the database
Log.d(TAG, "adding new user to database");
firebaseMethods.addNewUser(email, username);
Toast.makeText(activity_register.this, "SignUp successful", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
}
});
finish();
} else {
// User is signed out
Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onAuthStateChanged:signed _out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
setupFirebaseAuth();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
FirebaseMethods Code
package com.example.movies4u.Utils;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.example.movies4u.Models.User;
import com.example.movies4u.Models.UserAccountSettings;
import com.example.movies4u.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
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.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class FirebaseMethods {
private static final String TAG="FirebaseMethods";
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String userID;
private Context mContext;
public FirebaseMethods(Context context){
mAuth=FirebaseAuth.getInstance();
mFirebaseDatabase =FirebaseDatabase.getInstance();
myRef=mFirebaseDatabase.getReference();
mContext =context;
if(mAuth.getCurrentUser() !=null){
userID =mAuth.getCurrentUser().getUid();
}
}
public boolean checkIfUsernameExists(String username, DataSnapshot dataSnapshot){
User user =new User();
//Getting error in the below line
for (DataSnapshot ds: dataSnapshot.child(userID).getChildren()){
user.setUsername(ds.getValue(User.class).getUsername());
if(StringManipulation.expandUsername(user.getUsername()).equals(username)){
return true;
}
}
return false;
}
public void addNewUser(String email, String username){
User user=new User(email,username);
if(userID!=null)
{
myRef.child(mContext.getString(R.string.dbname_users))
.child(userID)
.setValue(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.d(TAG, "user added");
Toast.makeText(mContext, "user added", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "user not added");
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
UserAccountSettings settings = new UserAccountSettings(username, username);
myRef.child(mContext.getString(R.string.dbname_user_account_settings))
.child(userID)
.setValue(settings);
}
else {
Log.d(TAG, "user is null");
}
}
}
You are initializing the userID variable like this:
if(mAuth.getCurrentUser() != null){
userID =mAuth.getCurrentUser().getUid();
}
When registering, the user is not authenticated yet. Therefore, userID is null. You could check this with the debugger.
In the register method there should not be a method to call for currently authenticated user, since you are trying to register a new user and they are not able to login/authenticate just yet.
Instead, try passing the userDTO object you get from the data the future/potential user inputed and check for validity of username (and other invariants you might have) before allowing the registration.
Problem
This is the code for register activity and i want to make user register and also add user name and user id details in realtimedatabase. But app gets crashed after opening register activity
Error
FATAL EXCEPTION: main
Process: com.example.movies4u, PID: 27945
java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.firebase.auth.FirebaseAuth$AuthStateListener.onAuthStateChanged(com.google.firebase.auth.FirebaseAuth)' on a null object reference
at com.google.firebase.auth.zzl.run(com.google.firebase:firebase-auth##21.0.3:1)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7081)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
java
package com.example.movies4u;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
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.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.movies4u.Utils.FirebaseMethods;
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.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
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 activity_register extends AppCompatActivity {
TextView HaveAccount;
EditText inputUsername,inputEmail,inputPassword,inputConfirmPassword;
String username,email,password;
Button btnRegister;
FirebaseAuth mAuth;
ProgressBar pb;
private String userID;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseMethods firebaseMethods;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String append;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //Hide status Bar
setContentView(R.layout.activity_register);
firebaseMethods =new FirebaseMethods(activity_register.this);
HaveAccount= (TextView) findViewById(R.id.HaveAccount);
pb = findViewById(R.id.progressBar3);
inputUsername=findViewById(R.id.inputUsername);
inputEmail=findViewById(R.id.inputEmail);
inputPassword=findViewById(R.id.inputPassword);
inputConfirmPassword=findViewById(R.id.inputConfirmPassword);
btnRegister=findViewById(R.id.btnRegister);
username=inputUsername.getText().toString();
email=inputEmail.getText().toString();
password=inputPassword.getText().toString();
pb.setVisibility(View.GONE);
HaveAccount.setOnClickListener(view -> {
Intent loginintent=new Intent(activity_register.this,login_activity.class);
startActivity(loginintent);
});
mAuth=FirebaseAuth.getInstance();
btnRegister.setOnClickListener(view -> ValidateDataandDoRegister());
}
private void ValidateDataandDoRegister() {
String username=inputUsername.getText().toString().trim();
String email=inputEmail.getText().toString().trim();
String password=inputPassword.getText().toString().trim();
String confirmPassword=inputConfirmPassword.getText().toString().trim();
if(email.isEmpty()){
inputEmail.setError("Enter Email Address");
inputEmail.requestFocus();
pb.setVisibility(View.GONE);
}
else if(email.length()<10){
inputEmail.setError("Enter valid Email");
inputEmail.requestFocus();
pb.setVisibility(View.GONE);
}
else if(password.isEmpty()){
inputPassword.setError("Enter the password");
inputPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(password.length()<8){
inputPassword.setError("Password should be greater than 8 characters");
inputPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(confirmPassword.isEmpty()){
inputConfirmPassword.setError("Re-Enter the Password");
inputConfirmPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(confirmPassword.length()<8){
inputConfirmPassword.setError("Password should be greater than 8 characters");
inputConfirmPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(!password.equals(confirmPassword)){
inputPassword.setError("Password not matched");
inputPassword.requestFocus();
inputConfirmPassword.setError("Password not matched");
inputConfirmPassword.requestFocus();
inputPassword.setText("");
inputConfirmPassword.setText("");
pb.setVisibility(View.GONE);
}
else{
pb.setVisibility(View.VISIBLE);
doRegister(username,email,password);
}
}
private void doRegister(String username,String email, String password) {
pb.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if(task.isSuccessful()){
userID=mAuth.getCurrentUser().getUid();
// firebaseMethods.registerNewEmail(username,email,password);
setupFirebaseAuth();
sendVerificationEmail();
}
}).addOnFailureListener(e -> {
if(e instanceof FirebaseAuthUserCollisionException){
btnRegister.setEnabled(true);
inputEmail.setError("Email Already Registered");
pb.setVisibility(View.GONE);
inputEmail.requestFocus();
}
else{
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(activity_register.this, "Oops! Something Went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private void sendVerificationEmail() {
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(task -> {
if(task.isSuccessful()){
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(activity_register.this, "Email has been sent to your email address", Toast.LENGTH_SHORT).show();
}
else {
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Oops! failed to send verification email",Toast.LENGTH_SHORT).show();
}
});
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: Make sure the username is not already in use
if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
//to randomly generate key to make sure username is unique
append = myRef.push().getKey().substring(3,10);
Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
}
username = username + append;
//add new user to the database
firebaseMethods.addNewUser(email, username);
Toast.makeText(activity_register.this, "SignUp successful", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
}
});
finish();
} else {
// User is signed out
Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
Not sure, but try to replace this
if (task.isSuccessful()) {
to that
if(task != null && task.isSuccessful()){
(everywhere).
Task is nullable, and can return null (Google doesn't say this in the docs.
Also add the same check for user
if (mAuth.getCurrentUser() != null)
It could be null if user not signed in, and throw NullPointerEx when you try to call
getUid()
Problem
This is the code for register activity and i want to make user register and also add user name and user id details in realtimedatabase. But app gets crashed after opening register activity
Error
FATAL EXCEPTION: main
Process: com.example.movies4u, PID: 18933
java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.firebase.auth.FirebaseAuth$AuthStateListener.onAuthStateChanged(com.google.firebase.auth.FirebaseAuth)' on a null object reference
at com.google.firebase.auth.zzl.run(com.google.firebase:firebase-auth##21.0.3:1)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7081)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
Java
package com.example.movies4u;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
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.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.movies4u.Utils.FirebaseMethods;
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.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
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 activity_register extends AppCompatActivity {
TextView HaveAccount;
EditText inputUsername,inputEmail,inputPassword,inputConfirmPassword;
String username,email,password;
Button btnRegister;
FirebaseAuth mAuth;
ProgressBar pb;
private String userID;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseMethods firebaseMethods;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String append;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //Hide status Bar
setContentView(R.layout.activity_register);
firebaseMethods =new FirebaseMethods(activity_register.this);
HaveAccount= (TextView) findViewById(R.id.HaveAccount);
pb = findViewById(R.id.progressBar3);
inputUsername=findViewById(R.id.inputUsername);
inputEmail=findViewById(R.id.inputEmail);
inputPassword=findViewById(R.id.inputPassword);
inputConfirmPassword=findViewById(R.id.inputConfirmPassword);
btnRegister=findViewById(R.id.btnRegister);
username=inputUsername.getText().toString();
email=inputEmail.getText().toString();
password=inputPassword.getText().toString();
pb.setVisibility(View.GONE);
HaveAccount.setOnClickListener(view -> {
Intent loginintent=new Intent(activity_register.this,login_activity.class);
startActivity(loginintent);
});
mAuth=FirebaseAuth.getInstance();
btnRegister.setOnClickListener(view -> ValidateDataandDoRegister());
}
private void ValidateDataandDoRegister() {
String username=inputUsername.getText().toString().trim();
String email=inputEmail.getText().toString().trim();
String password=inputPassword.getText().toString().trim();
String confirmPassword=inputConfirmPassword.getText().toString().trim();
if(email.isEmpty()){
inputEmail.setError("Enter Email Address");
inputEmail.requestFocus();
pb.setVisibility(View.GONE);
}
else if(email.length()<10){
inputEmail.setError("Enter valid Email");
inputEmail.requestFocus();
pb.setVisibility(View.GONE);
}
else if(password.isEmpty()){
inputPassword.setError("Enter the password");
inputPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(password.length()<8){
inputPassword.setError("Password should be greater than 8 characters");
inputPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(confirmPassword.isEmpty()){
inputConfirmPassword.setError("Re-Enter the Password");
inputConfirmPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(confirmPassword.length()<8){
inputConfirmPassword.setError("Password should be greater than 8 characters");
inputConfirmPassword.requestFocus();
pb.setVisibility(View.GONE);
}
else if(!password.equals(confirmPassword)){
inputPassword.setError("Password not matched");
inputPassword.requestFocus();
inputConfirmPassword.setError("Password not matched");
inputConfirmPassword.requestFocus();
inputPassword.setText("");
inputConfirmPassword.setText("");
pb.setVisibility(View.GONE);
}
else{
pb.setVisibility(View.VISIBLE);
doRegister(username,email,password);
}
}
private void doRegister(String username,String email, String password) {
pb.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(task -> {
if(task != null ){
if(mAuth.getCurrentUser() != null){
userID=mAuth.getCurrentUser().getUid();
}
// firebaseMethods.registerNewEmail(username,email,password);
setupFirebaseAuth();
sendVerificationEmail();
// firebaseMethods.addNewUser(email, username);
}
}).addOnFailureListener(e -> {
if(e instanceof FirebaseAuthUserCollisionException){
btnRegister.setEnabled(true);
inputEmail.setError("Email Already Registered");
pb.setVisibility(View.GONE);
inputEmail.requestFocus();
}
else{
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(activity_register.this, "Oops! Something Went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private void sendVerificationEmail() {
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(task -> {
if(task != null && task.isSuccessful()){
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(activity_register.this, "Email has been sent to your email address", Toast.LENGTH_SHORT).show();
//fixing the bug
mAuth.signOut();
}
else {
btnRegister.setEnabled(true);
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Oops! failed to send verification email",Toast.LENGTH_SHORT).show();
}
});
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
//cannot get into this part of code
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user=firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: Make sure the username is not already in use
if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
//to randomly generate key to make sure username is unique
append = myRef.push().getKey().substring(3,10);
Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
}
username = username + append;
//add new user to the database
// firebaseMethods.addNewUser(email, username);
Toast.makeText(activity_register.this, "SignUp successful", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
}
});
finish();
} else {
// User is signed out
Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onAuthStateChanged:signed _out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
I am expecting to store the user data in a realtime database. But i am getting a null pointer exception after i enter into the register activity. I guess it is because of the null user. But i should get a non-null user, because i am implementing that method after the user clicking on the register button and after the all the fields are verified .
Your code's flow is wrong. You're adding AuthListener in onStart() as mAuth.addAuthStateListener(mAuthListener); but you're initializing this mAuthListener later in the doRegiter(), which means while adding it in onStart(), it's not initialized and null which gives the error Null Pointer Exception.
For the solution, you should call the function setUpFirebaseAuth in onStart before adding it to the mAuth as:
#Override
public void onStart() {
super.onStart();
setupFirebaseAuth();
mAuth.addAuthStateListener(mAuthListener);
}
I'm trying to create a login screen which will use Phone Number Authentication in Firebase. I wrote a code;
package com.example.logindeneme;
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.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneLoginActivity extends AppCompatActivity {
private Button SendVerificationButton, VerifyButton;
private EditText InputPhoneNumber, InputVerificationCode;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_login);
mAuth = FirebaseAuth.getInstance();;
SendVerificationButton = (Button) findViewById(R.id.send_ver_code_button);
VerifyButton = (Button)findViewById(R.id.verify_button);
InputPhoneNumber = (EditText) findViewById(R.id.phone_number_input);
InputVerificationCode = (EditText) findViewById(R.id.verification_code_input);
loadingBar = new ProgressDialog(this);
SendVerificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = InputPhoneNumber.getText().toString();
if(TextUtils.isEmpty(phoneNumber)){
Toast.makeText(PhoneLoginActivity.this, "Please enter your phone number first...", Toast.LENGTH_SHORT).show();
}
else{
loadingBar.setTitle("Phone Verification");
loadingBar.setMessage("please wait, while we are authenticating your phone...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
PhoneLoginActivity.this, // Activity (for callback binding)
callbacks); // OnVerificationStateChangedCallbacks
}
}
});
VerifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendVerificationButton.setVisibility(View.INVISIBLE);
InputPhoneNumber.setVisibility(View.INVISIBLE);
String verificationCode = InputVerificationCode.getText().toString();
if(TextUtils.isEmpty(verificationCode)){
Toast.makeText(PhoneLoginActivity.this, "Please write verification code first...", Toast.LENGTH_SHORT).show();
}
else{
loadingBar.setTitle("Verification Code");
loadingBar.setMessage("please wait, while we are verifying verification code...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, verificationCode);
signInWithPhoneAuthCredential(credential);
}
}
});
callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
loadingBar.dismiss();
Toast.makeText(PhoneLoginActivity.this, "Invalid Phone Number, Please enter correct phone number with your country code...", Toast.LENGTH_SHORT).show();
SendVerificationButton.setVisibility(View.VISIBLE);
InputPhoneNumber.setVisibility(View.VISIBLE);
VerifyButton.setVisibility(View.INVISIBLE);
InputVerificationCode.setVisibility(View.INVISIBLE);
}
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
loadingBar.dismiss();
Toast.makeText(PhoneLoginActivity.this, "Code has been sent, please check and verify.", Toast.LENGTH_SHORT).show();
SendVerificationButton.setVisibility(View.INVISIBLE);
InputPhoneNumber.setVisibility(View.INVISIBLE);
VerifyButton.setVisibility(View.VISIBLE);
InputVerificationCode.setVisibility(View.VISIBLE);
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
Toast.makeText(PhoneLoginActivity.this, "Congratulations, you're logged in successfully...", Toast.LENGTH_SHORT).show();
SendUserToMainActivity();
}
else {
String message = task.getException().toString();
Toast.makeText(PhoneLoginActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(PhoneLoginActivity.this,MainActivity.class);
startActivity(mainIntent);
finish();
}
}
But when I try to enter my phone number and want a code, always says "Invalid phone number". However, if I enter my number and random verify code in Test Phone Numbers in Firebase, and if I enter in my app; it works.
My country uses "+90" phone code. So I tried +9053XXXXXXXX, +90 53X XXX XX XX, +90-53X-XXX-XX-XX and etc. but never works.
Where is my fault? Can you fix it ?
#Wicaledon
Go to your firebase console.
In Settings, enter your add your SHA-1 key.
This will definitely work.
To get SHA-1 key
https://developers.google.com/android/guides/client-auth
In the register page, when a user clicks on the "ImageUserPhoto", he can pick an image from the gallery. My code works fine when he picks the photo and fills up all given fields. But if he doesn't pick any photo, the app crashes. How can I give a warning if he doesn't choose any photo in the same section where I check all the fields?
Thanks in advance!!
package com.ayon.austmart.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ayon.austmart.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
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 com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import de.hdodenhof.circleimageview.CircleImageView;
public class RegisterActivity extends AppCompatActivity {
CircleImageView ImgUserPhoto;
static int PReqCode = 1;
static int REQUESCODE = 1;
Uri pickedImgUri;
private EditText userEmail, userPassword, userPassword2, userName;
private ProgressBar loadingProgress;
private Button regBtn;
private Intent homeIntent;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
userEmail = findViewById(R.id.Email);
userPassword = findViewById(R.id.Password);
userPassword2 = findViewById(R.id.ConfirmPassword);
userName = findViewById(R.id.Name);
loadingProgress = findViewById(R.id.progressBarRegister);
regBtn = findViewById(R.id.buttonRegister);
loadingProgress.setVisibility(View.INVISIBLE);
mAuth = FirebaseAuth.getInstance();
ImgUserPhoto = findViewById(R.id.avatar);
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
final String password2 = userPassword2.getText().toString();
final String name =userName.getText().toString();
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
//Everything is ok..
createUserAccount(email,name,password);
}
}
});
ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 22)
{
checkAndRequestForPermission();
}
else
{
openGallery();
}
}
});
}
private void createUserAccount(String email, final String name, String password) {
//this method create user account with valid email and pass
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
//user account is created successfully
showMessage("Account Created!");
//now update the pro pic and username
updateUserInfo(name,pickedImgUri,mAuth.getCurrentUser());
}
else
{
showMessage("Account creation failed"+task.getException().getMessage());
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
}
});
}
private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser){
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("user_photos");
final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uploaded successfully
//getting image url
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// uri contains user image url
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
//user info updated successfully
showMessage("Register Complete!");
updateUI();
}
}
});
}
});
}
});
}
private void updateUI() {
homeIntent = new Intent(getApplicationContext(), Home.class);
startActivity(homeIntent);
finish();
}
//message show
private void showMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
private void openGallery() {
//Open gallery intent and wait for user to pick an image
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUESCODE);
}
public void checkAndRequestForPermission()
{
if(ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE))
{
Toast.makeText(RegisterActivity.this,"Please accept for required permission",Toast.LENGTH_SHORT ).show();
}
else
{
ActivityCompat.requestPermissions(RegisterActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PReqCode);
}
}
else
openGallery();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUESCODE && data !=null)
{
//user has successfully picked an image...
//saving its reference to a Uri variable
pickedImgUri = data.getData();
ImgUserPhoto.setImageURI(pickedImgUri);
}
}
}
your pickedImgUri is null if the user does not select the image from gallery.
So when you call createUserAccount() when register button is clicked and user has not selected the image pickedImgUri is not updated as per your code.
Hence updateUserInfo() will fail calling an exception which causes the crash.
please add a null checker like
if(pickedImgUri!=null){
//then update the user account
}
If you are interested in forcing the user to select the profile photo then simply use above checker and alert user to please select a photo first but i'd advice against that. Not everyone likes to upload a photo. use any generic avatar png file instead when user does not want to update/remove the avatar.
Happy coding
Thanks a lot!! I have added a few lines and it worked!!! Thank you very much!!
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
if(pickedImgUri == null)
{
showMessage("Please select an image");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else {
createUserAccount(email, name, password);
//Everything is ok..
}
}
}
});