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();
}
}
});
}
}
Related
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.
}
}
};)
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());
}
}
});
}
}
}
});
}
}
});
}
I'm adding reset password in my app, every thing goes ok, but when i it tried to test it a toast showed to me with this message "the email address is badly formatted"?
I tried to change input type to textEmailAddress bud doesn't work
public class ResetPasswordActivity extends AppCompatActivity {
EditText resetPassword;
Button resetbtn;
ProgressBar resetBar;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
resetPassword =findViewById(R.id.emailreset);
resetBar = findViewById(R.id.resetbar);
resetbtn = findViewById(R.id.resetbtn);
resetBar.setVisibility(View.GONE);
firebaseAuth = firebaseAuth.getInstance();
resetbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resetBar.setVisibility(View.VISIBLE);
firebaseAuth.sendPasswordResetEmail(resetPassword.toString()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
resetBar.setVisibility(View.GONE);
if (task.isSuccessful()){
Toast.makeText(ResetPasswordActivity.this,"Password sent to your Email",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ResetPasswordActivity.this,task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
});
}
}
You're doing:
resetPassword =findViewById(R.id.emailreset);
And then:
firebaseAuth.sendPasswordResetEmail(resetPassword.toString())
This means that you're passing the actual view into the call to Firebase, not the value that the user entered.
You're probably looking for:
resetPassword.getText().toString()
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.
I am making a simple authentication app in Android using Firebase authentication. Till now I am successful in signing the user in, however the issue is that the user remains signed in, and I can't find a way to sign him out.
Here is my MainActivity.java code
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//tracking the sign in and singn out operations
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user!=null){
System.out.println("User logged in");
}
else{
System.out.println("User not logged in");
}
}
};
}
public void onStart(){
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
public void onStop(){
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
public void buttonClicked(View view){
EditText editemail = (EditText) findViewById(R.id.email);
EditText editpass = (EditText) findViewById(R.id.password);
String email = editemail.getText().toString();
String password = editpass.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
Toast.makeText(MainActivity.this, "Authentication Success.",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,Success.class));
// 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()) {
// Log.w(TAG, "signInWithEmail", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
Use this code FirebaseAuth.getInstance().signOut();
You can simply call this
FirebaseAuth.getInstance().signOut();
If you want to perform some action after sign out then use this one.
public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MyActivity.this, SignInActivity.class));
finish();
}
});
}
}
This can be solved by using AuthStateListener
//Declaration and defination
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
//Do anything here which needs to be done after signout is complete
signOutComplete();
}
else {
}
}
};
//Init and attach
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.addAuthStateListener(authStateListener);
//Call signOut()
firebaseAuth.signOut();
Snippet : https://codepad.co/snippet/aPeehdoD
Firebase auth is provide signout method.
FirebaseAuth.getInstance().signOut();
Try This
FirebaseAuth fAuth = FirebaseAuth.getInstance();
fAuth.signOut();
if you are using firebaseAuthUI then recommended method is
public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MyActivity.this, SignInActivity.class));
finish();
}
});
}
}
according to firebaseAuthUI github Guide.
use this`
findViewById(R.id.signout).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(currentActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);//makesure user cant go back
startActivity(intent);
}
});`
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseAuth.getInstance().signOut();
Intent intent = new Intent(SettingsActivity.this,SignInActivity.class);
startActivity(intent);
}
});
This one just signs you out from the current application .
if you are using a fragment do this
AuthUI.getInstance().signOut(getActivity());
if you are using an activity do this
AuthUI.getInstance().signOut(getApplicationContext);
cheers!
For complete log out I would recommend :
mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
There have several way to sign out user:
1. FirebaseUI: Refarence
Add depenencies:
dependencies {
implementation 'com.firebaseui:firebase-ui-auth:4.0.0'
}
Then:
public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MyActivity.this, SignInActivity.class));
finish();
}
});
}
}
2. Kotlin: Referance
Use Android default Authentication dependency, ex: com.google.firebase:firebase-auth:16.0.1
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
3. Default with java:
Use Android default Authentication dependency, ex: com.google.firebase:firebase-auth:16.0.1
FirebaseAuth mAuth = FirebaseAuth.getInstance();
try {
mAuth.signOut();
Toast.makeText(this, "User Sign out!", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
Log.e(TAG, "onClick: Exception "+e.getMessage(),e );
}
FirebaseAuth.getInstance().signOut();
Then, to detect the sign-in status:
private FirebaseAuth mAuth = FirebaseAuth.getInstance()
public static boolean mAuthSignIn() {
if (mAuth != null) {
FirebaseUser user = mAuth.getCurrentUser();
return user != null;
}
return false;
}
Try this one it is working for me.
FirebaseAuth.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(YOUR CURRENT ACTIVITY, ACTIVITY IN WHICH YOU WANT TO MOVE));
finish();
}
});