Why FirebaseAuth.getCurrentUser() is returning null - android

I’m reprogramming/reproducing whatsapp for android and I’m facing a problem.
In my app, users have to register their self to use it. After the registration, users are directed to the MainActivity where they can start chatting with their friends or they can complete their profile. Users can Login to the app but only if they Logout. They don't have to Login after the registration.
I'm using the Firebase technologies, Firebase Authentication, Firebas database, Firebase storage on the app. When the user complete his registration, his information are stored in the real-time database.
Here's the problem I registered my self and instead of going directly to the MainActivity, i'm directed to LoginActivity and that can happen only if
the currentUser is null. If the currentUser is null, it means that FirebasAuth.getCurrentUser() is returning null.
I want to understand why is this hapenning ? Why my currentUser variable is null when I registered my self only few seconds ago ? Why is FirebasAuth.getCurrentUser()
returning null when i can see that my informations are stored on the Firebase database?
Here's the code of RegisterActivity :
public class RegisterActivity extends AppCompatActivity {
private Button createUser;
private EditText registerEmail, registerPassword;
private TextView haveAccount;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth=FirebaseAuth.getInstance();
RootRef= FirebaseDatabase.getInstance().getReference();
initializeFields();
haveAccount.setClickable(true);
haveAccount.setFocusable(true);
haveAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToLoginActivity();
}
});
createUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createNewAccount();
}
});
}
private void createNewAccount() {
final String email=registerEmail.getText().toString();
String password=registerPassword.getText().toString();
if (TextUtils.isEmpty(email))
Toast.makeText(this,"Please enter an address mail to create an account",Toast.LENGTH_LONG).show();
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter an address mail to create an account", Toast.LENGTH_LONG).show();
} else {
loadingBar.setTitle("Create new Account");
loadingBar.setMessage("Please wait, while we creating account for you");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
mAuth=new FirebaseAuth(FirebaseApp.initializeApp(RegisterActivity.this));
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if (task.isSuccessful()) {
String currentUserID=mAuth.getCurrentUser().getUid();
RootRef.child("Users").child(currentUserID).setValue(email);
SendUserToMainActivity();
Toast.makeText(RegisterActivity.this, "Your account is created successfully", Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
else {
String message=task.getException().toString();
Toast.makeText(RegisterActivity.this,"Error " + message,Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
private void initializeFields() {
createUser=findViewById(R.id.register_button);
registerEmail=findViewById(R.id.register_email);
registerPassword=findViewById(R.id.register_password);
haveAccount=findViewById(R.id.already_have_account_link);
loadingBar= new ProgressDialog(this);
}
private void SendUserToLoginActivity() {
StartActivity(RegisterActivity.this,LoginActivity.class);
}
private void SendUserToMainActivity() {
StartActivity(RegisterActivity.this,MainActivity.class);
}
private void StartActivity(Context c, Class<?> activity){
Intent i=new Intent(c,activity);
if(activity.equals(MainActivity.class)) {
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
} else
startActivity(i);
}
And here's the code of my MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ViewPager myViewPager;
private TabLayout myTabLayout;
private TabsAccessorAdapter myTabsAccessorAdapter;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
RootRef= FirebaseDatabase.getInstance().getReference();
mToolbar=findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("WhatsApp");
myViewPager=findViewById(R.id.main_tabs_pager);
myTabsAccessorAdapter=new TabsAccessorAdapter(getSupportFragmentManager());
myViewPager.setAdapter(myTabsAccessorAdapter);
myTabLayout = findViewById(R.id.main_tabs);
myTabLayout.setupWithViewPager(myViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.options_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==R.id.main_find_friends_option){
}
if (item.getItemId()==R.id.main_create_group_option){
requestNewGroup();
}
if (item.getItemId()==R.id.main_settings_option){
SendUserToSettingsActivity();
}
if (item.getItemId()==R.id.main_logout_option){
mAuth.signOut();
SendUserToLoginActivity();
}
return true;
}
#Override
protected void onStart() {
super.onStart();
currentUser = mAuth.getCurrentUser();
if(currentUser==null)
SendUserToLoginActivity();
else
verifyUserID();
}
private void SendUserToLoginActivity() {
StartActivity(MainActivity.this,LoginActivity.class);
}
private void StartActivity(Context c, Class<?> activity){
Intent i=new Intent(c,activity);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}

After creating or signing in the user, it takes a brief moment before FirebaseAuth.getInstance().getCurrentUser() picks up this change. So if you're using that variable in the meantime, you will get null.
There are two options to work around this:
Use the Task<AuthResult> task that you get after creating the user. So String currentUserID=task.getResult().getUser().getUid(); and pass that along to the new activity in the intent.
Use an AuthStateListener to pick up the authentication state in the next activity.
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// Sign in logic here.
}
}
};)

Related

Relating Firebase Auth users with Firebase Database

I have an login app for users. But I add email and password from firebase console.
And I have another app for admin users where I can add the user info and details.
I'm adding names etc but I'am also adding the Uid from Firebase Auth so I am hoping to link these.
I just have a LoginActivity and a MainActivity in the User app. When the user get the credentials from admin they can log in and they get to MainActivity. It's in the users MainActivity I want to get the stored data for the current user that was stored in firebase database from the admin app.
Also I have added both the user app and the admin app in Firebase.
Can someone help me?
UserApp
LoginActivity:
public class LoginUserActivity extends AppCompatActivity {
EditText etuseremail, etuserpassword;
Button btnloginuser;
TextView tvforgotpassword;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_user);
mAuth = FirebaseAuth.getInstance();
etuseremail = (EditText)findViewById(R.id.et_userloginemail);
etuserpassword = (EditText)findViewById(R.id.et_userloginpassword);
btnloginuser = (Button)findViewById(R.id.btn_loginuser);
tvforgotpassword = (TextView)findViewById(R.id.tv_forgotpassword);
btnloginuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginuser();
}
});
tvforgotpassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void loginuser() {
String email = etuseremail.getText().toString().trim();
String password = etuserpassword.getText().toString().trim();
if (email.isEmpty()) {
etuseremail.setError("Epost addresse mangler");
etuseremail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
etuseremail.setError("Bruk en gyldig epost addresse");
etuseremail.requestFocus();
return;
}
if (password.isEmpty()) {
etuserpassword.setError("Passord mangler");
etuserpassword.requestFocus();
return;
}
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull #NotNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(LoginUserActivity.this, UserToolActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else{
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}

Null pointer exception when the widget is already initialized

I'm trying to change the user authentication email.
CustomDialogBox
public class ConfirmPasswordDialogBox extends Dialog implements android.view.View.OnClickListener {
private ImageButton cancel, confirm;
private EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
cancel.setOnClickListener(this);
confirm.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
Activity where null pointer exception is thrown
public class EditProfileActivity extends AppCompatActivity {
private EditText descript, firstName, lastName, email;
private Button updatebtn;
private ImageButton back;
private Context mcontext;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseMethods firebaseMethods;
private String userID;
private ProgressDialog pb;
private UserInformation userInformationx;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mcontext = EditProfileActivity.this;
descript = findViewById(R.id.descript);
firstName = findViewById(R.id.firstName);
email = findViewById(R.id.email);
lastName = findViewById(R.id.lastName);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
firebaseMethods = new FirebaseMethods(mcontext);
pb = new ProgressDialog(this);
pb.setMessage("Updaing Profile ...");
pb.setCancelable(true);
pb.setCanceledOnTouchOutside(false);
init();
setupFirebaseAuth();
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}
The EditText widget is already intialized, still email.getText.toString() is throwing null. I'm just passing the string value to a method, which is called when a button is clicked in Dialog box.
I've tried and debug all possible ways I know.
I'm just trying to update the user authentication email in firebase.
The EditText widget is already intialized, still email.getText.toString() is throwing null.
Actually the EditText email is only intialized in the onCreate of the activity, this means that it's only initialized when you open the activity using startActivity(intent).
Edit - Since you're calling the ConfirmPasswordDialogBox from the EditProfileActivity, something along the following lines should work.
public class ConfirmPasswordDialogBox extends Dialog {
private ImageButton cancel, confirm;
public EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
//cancel.setOnClickListener(this);
//confirm.setOnClickListener(this);
}
public void setOnClickListeners(View.OnClickListener listener) {
cancel.setOnClickListener(listener);
confirm.setOnClickListener(listener);
}
/*
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
*/
}
public class EditProfileActivity extends AppCompatActivity implements android.view.View.OnClickListener {
//Other code
//At some point in some method you'll create the dialog
//Say you create the dialog object here. Now set this activity as the onClickListener
dialog.setOnClickListeners(this);
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = dialog.confirm_password.getText().toString();
if(!mpassword.equals("")){
//Now you can directly call the method
updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}

two different app logins on single Firebase project Problem

I have a Problem in the login. Basically, I tell you my scenario.
I have two apps both are connected with a single firebase project.
One app contains driver login and other app contain customer login
When I open a customer app and register the new customer. The customer is successfully registered. And then I open the driver app and entered the customer credential means (Customer email & password) its login successfully and open the driver activity and vice-versa.
how to fix this issue I am using firebase.
customer login activity
public class CustomerLoginActivity extends AppCompatActivity {
private EditText mEmail, mPassword;
private Button mLogin, mRegistration;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null ){
Intent intent = new Intent(CustomerLoginActivity.this, CustomerMapActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.login);
mRegistration = (Button) findViewById(R.id.registration);
mRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(CustomerLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(CustomerLoginActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
}else{
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(CustomerLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(CustomerLoginActivity.this, "sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
}
driver login activity
public class DriverLoginActivity extends AppCompatActivity {
private EditText mEmail, mPassword;
private Button mLogin, mRegistration;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
Intent intent = new Intent(DriverLoginActivity.this, DriverMapActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.login);
mRegistration = (Button) findViewById(R.id.registration);
mRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(DriverLoginActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
}else{
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Drivers").child(user_id).child("name");
current_user_db.setValue(email);
}
}
});
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(DriverLoginActivity.this, "sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
}
My database rules
Firebase authentication doesn't differentiate between different "types" of users, like you're trying to do. You'll have to implement some custom logic of your own in your app(s) to handle these situations. The base signInWithEmailAndPassword() method will always work if you provide it correct credentials... so what you need to do is in your app code, BEFORE you call the signInWithEmailAndPassword() method, check to see if the provided username is "allowed" to use this version of the app...
So as soon as you get their username, before calling that signIn method, make a query to the database to determine whether that username belongs to a "customer" or a "driver". I assume you have something like a /users node in your database - if you don't, you'll need to create one, there's no way around it. If you're not sure how to query the database, use the addListenerForSingleValueEvent() method... check out the official docs for examples/syntax.
Once you've determined whether the username is for a customer vs a driver... you will need to implement logic to decide whether they are allowed to proceed to the signIn method.
If they are a "customer" and this is the "customer" app, then allow the code to proceed to the signIn method... but if the username comes back as a "driver" then stop the code and display an error to the user.
Similarly for the "driver" app, if the username comes back as being for a "driver" then allow the code to proceed to the signIn method... but if it comes back as a "customer" then stop the code and display an error to the user.

When my app is destroyed firebase doesn't store my user and it skips the log in page

When I start my app the 1st page is the login, after I successfully log in the new intent brings me to the main menu with my username at the side. When I destroy the app by right the username should be stored at the main menu, but it removes the username and is empty. Hereby I have attached the code for my login.
private EditText PasswdEdit;
private EditText EmailEdit;
private Button LoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
mAuth = FirebaseAuth.getInstance();
PasswdEdit = findViewById(R.id.PasswdEdit);
EmailEdit = findViewById(R.id.EmailEdit);
LoginBtn = findViewById(R.id.LoginBtn);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null)
{
startActivity(new Intent(LogIn.this,MainMenu.class).putExtra("UserName",EmailEdit.getText().toString()));
}
}
};
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSingIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
public void onBackPressed() {
}
private void startSingIn (){
String email = EmailEdit.getText().toString();
String passwd = PasswdEdit.getText().toString ();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(passwd))
{
Toast.makeText(LogIn.this,"Fields are empty",Toast.LENGTH_LONG).show ();
}
else
{
mAuth.signInWithEmailAndPassword(email,passwd).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(LogIn.this,"Please check your credentials",Toast.LENGTH_LONG).show ();
}
if (task.isSuccessful()) {
FirebaseUser userLogIn = mAuth.getCurrentUser();
}
}
});
}
}
The user was still stored but what I did earlier was I extract the username from the editbox, so when the app is destoryed and restarted the editbox is empty because that page is skipped.
Hereby I have attached the code to overcome this problem.
if (firebaseAuth.getCurrentUser() != null)
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
startActivity(new Intent(LogIn.this,MainMenu.class).putExtra("UserName",user.getEmail()));
}
if (firebaseAuth.getCurrentUser() == null)
{
}

Null pointer exception when login fields are empty - Firebase

I have this code where the user enters his credentials and logs in.
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private FirebaseAuth mAuth;
private Toolbar mToolbar;
private TextInputEditText mLoginEmail;
private TextInputEditText mLoginPassword;
private Button mLoginBtn;
private Button mForgotPass;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mToolbar = findViewById(R.id.login_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Login");
mAuth = FirebaseAuth.getInstance();
mProgress = new ProgressDialog(this);
mLoginEmail = (TextInputEditText)findViewById(R.id.login_email);
mLoginPassword = (TextInputEditText)findViewById(R.id.login_password);
mLoginBtn = (Button)findViewById(R.id.login_create_btn);
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = mLoginEmail.getText().toString();
String pass = mLoginPassword.getText().toString();
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(pass)){
mProgress.setTitle("Logging in");
mProgress.setMessage("Please wait while we check your credentials");
mProgress.setCanceledOnTouchOutside(false);
mProgress.show();
loginUser(email,pass);
}
}
});
mForgotPass = (Button)findViewById(R.id.login_forgot_password);
mForgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this,ForgotPasswordActivity.class);
startActivity(i);
}
});
}
private void loginUser(final String email, final String pass) {
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mProgress.dismiss();
sendToMain();
} else {
mProgress.hide();
Toast.makeText(LoginActivity.this, "Can not login", Toast.LENGTH_SHORT).show();
Log.d(TAG, String.valueOf(task.getException()));
}
}
});
}
private void sendToMain() {
Intent mainIntent = new Intent(LoginActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
To achieve a login procedure I call the signInWithEmailAndPassword(email,pass) method as you see above. Just for validation purposes I want to have a toast saying that you should fill both email and password fields. As it is now, I get an exception when I click the login button. How to fix that?
This is the exception.
at com.google.android.gms.common.internal.zzbq.zzgm(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at theo.tziomakas.news.LoginActivity.loginUser(LoginActivity.java:90)
at theo.tziomakas.news.LoginActivity.access$300(LoginActivity.java:22)
at theo.tziomakas.news.LoginActivity$1.onClick(LoginActivity.java:70)
Thanks,
Theo.
Found your error, the following:
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(pass))
should be an && and not a ||:
if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass))
You want both to be not null to call your login.

Categories

Resources