With my current login activity, I can log in just fine, however I need to get Uid throughout my project.
This is my current login activity:
//authenticate user
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// 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.
progressbar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
lPass.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MapsActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
How do I get the user Uid from the login and have it be accessible to all my other activities?
Thanks
You can get user info from the FirebaseUser object. In order to achieve this, please use the following code:
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
String userEmail = firebaseUser.getEmail();
}
}
};
FirebaseAuth.getInstance().getCurrentUser().getUid();
This line will give you the user ID.
This is a way to get all details available for user logged in from firebase.
FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance();
FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
// User Name
mFirebaseUser.getDisplayName();
// User ID
mFirebaseUser.getUid();
// Email-ID
mFirebaseUser.getEmail();
// User-Profile (if available)
mFirebaseUser.getPhotoUrl();
Using FirebaseAuth you can get user uid,
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
Log.d(TAG," UserId : "+firebaseUser.getUid()+" , DisplayName"+firebaseUser.getDisplayName());
Related
I am trying to authenticate users with email and password through firebase. But it shows can not resolve updateUI(user).
Here's this part of the code.
public void OnContinue(View view) {
if(hasClickedCountinueOnce){
EditText emailTextBox = (EditText)findViewById(R.id.email);
String user = userNAAME.getText().toString();
String passwordText = password.getText().toString();
String email = emailTextBox.getText().toString();
//todo manage new account here
if(!user.isEmpty() && !passwordText.isEmpty() ){
mAuth.createUserWithEmailAndPassword(email, passwordText)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("SignInFailed", "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w("SignInFailed", "createUserWithEmail:failure", task.getException());
Toast.makeText(SignUP.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
}
}
The code is from the Firebase Quickstart-Android project. This is what it does. You can implement something similar:
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null) {
mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail()));
mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
mStatusTextView.setText(R.string.signed_out);
mDetailTextView.setText(null);
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
If I am getting your problem rightly with the limited code that u shared above, the function call "updateUI" refred here (https://firebase.google.com/docs/auth/android/password-auth) is the call/function you have to write on your own to update ur UI elements, and as #BobSnyder mentioned here's the link to a reference code (https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/EmailPasswordActivity.java#L209)
You need to write your own custom UpdateUI method in your MainActivity and write the code for what your app should do when a user is logged in with a condition for example if(user!=null).
Your coding for authentication is working.
What is the purpose of FirebaseUser user = mAuth.getCurrentUser(); inside successful login ?
To get current user, you have to implement Auth Change Listner after success login as,
private FirebaseAuth.AuthStateListener mAuthListener;
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null){
updateUI(user);
}
}
};
mAuth.addAuthStateListener(mAuthListener);
(Use different variable name)
private void updateUI(#Nullable GoogleSignInAccount account) {
if (account != null) {
mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
mStatusTextView.setText(R.string.signed_out);
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
UPDATE
the problem is i cant show up user email on EditText
i tried to put onStart and onStop mauth listener and then when i run the app and enter this activity the user see as null and kick me back to login activity. so is there any solution on this ?
public class ProfileActivity extends AppCompatActivity {
private EditText newEmail;
private FirebaseAuth.AuthStateListener mauthListener;
private FirebaseAuth mauth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//get current user
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//get firebase auth instance
mauth = FirebaseAuth.getInstance();
newEmail = (EditText) findViewById(R.id.email1);
//tracking the sign in and singn out operations
mauthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
finish();
}
}
};
setDataToView();
}
private void setDataToView() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
newEmail.setText("" + user.getEmail());
}
}
UPDATED
i cant show up user email on EditText, whats wrong now ?
So firebase user in your setDataToView() is null because you are setting the usermail to Edittext without check if is null to fix that you have two possible ways.
One is do that :
mauthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
finish();
}else{
newEmail.setHint("" + user.getEmail());
}
}
};
other way is do that:
private void setDataToView() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
newEmail.setHint("" + user.getEmail());
}
}
Looking at the documentation, I just found this:
FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress = "user#example.com";
auth.sendPasswordResetEmail(emailAddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
I have a problem because I need to implement forgot password functionality in the login activity, where FirebaseAuth is null because user is not logged in, so how can I figure it out?
The FirebaseAuth.getInstance() method will never return null, so your code will work.
It's the FirebaseAuth.getInstance().getCurrentUser() method that will return null if the user is not logged in.
From the Android Firebase Authentication getting started documentation:
Declare an instance of FirebaseAuth
private FirebaseAuth mAuth;
In the onCreate() method, initialize the FirebaseAuth instance.
mAuth = FirebaseAuth.getInstance();
When initializing your Activity, check to see if the user is currently
signed in.
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
And the code you have in your question is from the send a password reset section:
You can send a password reset email to a user with the
sendPasswordResetEmail method. For example:
FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress = "user#example.com";
auth.sendPasswordResetEmail(emailAddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
The emailAddress variable is specified here, because the user is not logged in.
I have created an app with the database maintaining in Firebase. I have completed the user registration part and here is the coding I used,
if(edtUsrNameS.length() >0 && edtPassS.length() >0 &&edtEmailS.length() >0) {
strUsrS = edtUsrNameS.getText().toString().trim();
strPassS = edtPassS.getText().toString().trim();
strEmailS = edtEmailS.getText().toString().trim();
if(Constant.isValidEmail(strEmailS)){
edtEmailS.setError(null);
Map<String, String> parameters = new HashMap<>();
parameters.put(Constant.TAG_USER, strUsrS.trim());
parameters.put(Constant.TAG_PASS, strPassS.trim());
parameters.put(Constant.TAG_EMAIL, strEmailS.trim());
String pushId = mFirebaseInstance.getReference(Constant.FIREBASE_LOGIN).getRef().push().getKey();
parameters.put(Constant.TAG_KEY, pushId.trim());
mFirebaseInstance.getReference(Constant.FIREBASE_LOGIN).getRef().child(strUsrS.trim()).setValue(parameters);
Toast.makeText(Login_Reg_Activity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
finish();
Intent inMain = new Intent(Login_Reg_Activity.this, Login_Reg_Activity.class);
startActivity(inMain);
}else{
edtEmailS.setError("Enter a valid Email");
}
}else{
Toast.makeText(Login_Reg_Activity.this, "Fill all detail", Toast.LENGTH_SHORT).show();
}
After the successful registration, the data are stored in the users table in Firebase like this:
My doubt is that how to login using the credential username and mobile. I have tried by the reference link, but I couldn't succeeded. So, my kind request is to direct me to do this. Also, how to restrict the duplication on user registration?
Thanks in advance.
Step 1:
make sure you have enabled the password login in firebase console as shwon below in the picture
Use Below Code For Login with email and Pwd
FirebaseAuth mAuth = FirebaseAuth.getInstance(); // same auth as you used for regestration process
mAuth.signInWithEmailAndPassword("abc#abc.com","pwd")
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
}
}})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
when you get successfully login than auth change listner will be invoke
Auth Change Listner
private FirebaseAuth.AuthStateListener mAuthListener;
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null){
}
}
};
mAuth.addAuthStateListener(mAuthListener);
FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;
EditText name, email, password;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("########", "onAuthStateChanged:signed_in:" + user.getUid());
}
else{
// User is signed out
Log.d("########", "onAuthStateChanged:signed_out");
}
}
};
name = (EditText) findViewById(R.id.input_name);
email = (EditText) findViewById(R.id.input_email);
password = (EditText) findViewById(R.id.input_password);
submit = (Button) findViewById(R.id.btn_signup);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString()).addOnCompleteListener(SignUp.this, new OnCompleteListener < AuthResult > () {
#Override
public void onComplete(#NonNull Task < AuthResult > task) {
Log.d("###########", "signInWithEmail:onComplete:" + task.isSuccessful());
}
});
The Task.isSuccessful() always returns false and I am not able to add any user.
I have enabled email authentication on Firebase and am able to add users from the forge itself, i am left with no way to debug and figure out where the issue is.
All other settings like adding dependencies and copying the configuration file obtained from Firebase into the app directory have been done. Please help.
I encountered the same problem, and decided to create a user from the firebase console. Then the error displayed in the image came up. The password is required to be at least 6 characters long. When signing up a new user ensure that the length of password is at least six and it should work.
I attached addOnFailureListener() and it abused:
The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.
private void register(final String user, String email,final String password) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser firebaseUserLcl = auth.getCurrentUser();
String userIdLcl = firebaseUserLcl.getUid();
l.a("userIdLcl="+userIdLcl);
DatabaseReference referenceLcl = FirebaseDatabase.getInstance().getReference("Users").child(userIdLcl);
HashMap<String, String> mapLcl = new HashMap();
mapLcl.put("id", userIdLcl);
mapLcl.put("email", email);
mapLcl.put("password", password);
mapLcl.put("ImageURL", "default");
referenceLcl.setValue(mapLcl).addOnCompleteListener(taskPrm -> {
if (taskPrm.isSuccessful()) {
Intent intentLcl = new Intent(RegisterActivity.this, MainActivity.class);
intentLcl.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentLcl);
finish();
}else {
Toast.makeText(RegisterActivity.this, "Signing failed,", Toast.LENGTH_LONG).show();
}
});
} else {
// l.a(task.getException().getCause());
Toast.makeText(RegisterActivity.this, "You cannot register with this email or password", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener( e->
l.a(e.getMessage()) //logging
);
}