I am a newbie in Firebase. Recently I am trying to save users into Firebase but I can't. When I generate the APK and run it onto the real device(Not Emulator), the new user does not add it into the Firebase. Also, no errors shown up. Task executed properly and go to OTPActivity. Here is my complete code:
public void saveUser()
{
firebaseAuth.createUserWithEmailAndPassword(emailAddress.getText().toString(),password.getText().toString()).addOnCompleteListener(ChatUserSignUpActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseUser user = firebaseAuth.getCurrentUser();
Intent intent = new Intent(ChatUserSignUpActivity.this, OTPActivity.class);
intent.putExtra("phoneNum",emailAddress.getText().toString());
startActivity(intent);
}
else
{
Toast.makeText(ChatUserSignUpActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
Please help me. Thanks in advance.
When you authenticate your users with email and password, no data is saved into Firestore, nor in the Realtime Database. If you need to save the database in the database, you need to write code for that. So once your user is authenticated, you can get the data from the FirebaseUser object and write it to the database of your choice.
Related
I want to delete user from firebase authentication and also want to delete data from real-time database if the user doesn't verify email address with in 1 hours. Deleting a user is easy but if doesn't verify in 1 hour then how could I do this? The problem is that firebase is server less.
Write and deploy a scheduled function that periodically:
Queries your database for users who have not verified (you will need a child to record that).
Delete the database record and also delete the user account.
You will need to use the Firebase Admin SDK for both of these steps.
It's so easy! just create a real-time database of the unverified user database. and when the user signup the time will be also registered in the database. So when the apps start it check the unverified users and there you write the if-else statement if the difference between time is greater than 1hour the user will be deleted.
It's so simple as I said :)
Run firebaseAuth.getCurrentUser().isEmailVerified() function inside signInWithEmailAndPassword function to see if user is verified or not. if user is verfied then only create users database otherwise give an exception and break the function, it won't save unverified users data.
firebaseAuth.signInWithEmailAndPassword(Email,Pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
if (firebaseAuth.getCurrentUser().isEmailVerified()){
FirebaseUser user = firebaseAuth.getCurrentUser();
Uid = user.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.hasChild(Uid)){
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(Uid);
HashMap<String,String> userMap = new HashMap<>();
userMap.put("Name","default");
userMap.put("email",Email);
databaseReference.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
//call your function here when user sign in first time after email verification
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
//call your function when user already registered and verified
//and already saved his information to database
}else{
//show your exception here
}
}else{
//show your exception here
}
}
});
The situation is the following:
The activity started on app's launch (let's call it splash activity, because used for some checkings and for read/write some settings) is made by frameworks and the last one of them has firebase signInWithEmailAndPassword whose addOnCompleteListener contains the code for starting a new activity (let's say the main activity).
one of the options of the (so called) main activity's menu is firebase signOut, when i tap it the current user signs out but the signInWithEmailAndPassword (coded into the last fragment of previous activity) is called again!
is it because i splitted sign-in and sign-out in two different activities?
can anybody kindly help me with that, thanks in advance.
here is code schema:
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// read some data from realtime database
database
.getReference(path)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
get snapshot data ...
// Store them into shared preferences
mSettings
.edit()
.putStringSet("STRING_SET_KEY", dataSet)
.apply();
// Update some Realtime database data
database
.getReference(path)
.updateChildren(newData)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// Start new activity
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
});
});
});
});
}
});
});
p.s. - i noticed because the signOut() kicks out the firebase user and when the signInWithEmailAndPassword is called again i got an error because it's not possible to read realtime database
You may check whether the user is still sign in or not.
According to this link: https://firebase.google.com/docs/auth/android/manage-users
This code put at the onCreateView...
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
// Start new activity
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
} else {
// No user is signed in
}
I'm using Firebase Authentication in my app (email and password auth).
In the onStart() method of my Login activity I retrieve the current user using:
FirebaseUser currentUser = mAuth.getCurrentUser();
The problem comes when the user is deleted from the database, the mAuth.getCurrentUser() method still retrieves the user and allows authentication.
How can I check if the user still exists?
Thx!
Try using something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("email").addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// used "email" already exists and is not deleted
} else {
// User does not exist. Add here your logic if the user doesn't exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or check some of the following SO questions and answers:
Firebase authentication for checking if the user exists in the database or not
Firebase Auth - with Email and Password - Check user already registered
You can use getInstance. This worked for me fine. You don't get an instance with it.
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
Delete the userdata and make the currentuser null:
Follow the below code.
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted.");
//Remove the information f the user from database.
}
}
});
The code below works great on android to confirm if the Firebase Auth user still exists (has not been deleted or disabled) and has valid credentials.
Deleting the Auth user from the firebase console does not revoke auth tokens on devices the user is currently logged in as the token is cached locally. Using reload() forces a check with the firebase auth server.
currentUser.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//User still exists and credentials are valid
}else {
//User has been disabled, deleted or login credentials are no longer valid,
//so send them to Login screen
}
}
});
I'm developing a social media application. In that, I need to check whether the user already exists or not when he login with otp (like in WhatsApp).
I have found similar questions like this in stackoverflow, but none of the questions have correct answer. Help me!
after a research, I found this answer.
In firebase, each phone number have a unique user id. So, if a user signs up from different devices, or reinstalls the application with a same phone number, he/she will get the same user Id. So with that, we can check our database like this:
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final FirebaseUser user = task.getResult().getUser();
String uid = user.getUid();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
final DocumentReference docRef = db.collection("users").document(uid);
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(final DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
//redirect to home page
}
else{
//redirect to sign up page
}
}
Hope this will help someone :)
You can just use the admin SDK and lookup the user by phone number:
https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data
admin.auth().getUserByPhoneNumber(phoneNumber)
.then(function(userRecord) {
// User found.
})
.catch(function(error) {
// User not found.
});
If you try to create an user that already exists, Firebase will throw you an exception. You can handle that exception to do what you want.
Hope this helps!
First store the Firebase Phone Auth in FirebaseDatabase after every successful registration, then add a check when user try and enter the phone number if it already exist in database, If present then you got your answer otherwise register the user.
I hope the concept is clear. Will update you with the code soon.
#Soorya. If you want to make your application like WhatsApp then you have to simply authenticate the user using phone number and OTP. When the user gets verified successfully then check whether user details are available in Firebase Database or FireStore. If available then simply redirect the user to home screen otherwise redirect the user to the registration page. For that refer below code snippet.
mFirebaseAuth
.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
goToNextActivity(((AuthResult) task.getResult()).getUser());
return;
}
}
});
private void goToNextActivity(FirebaseUser firebaseUser) {
FirebaseDatabase
.getInstance()
.getReference()
.child("your table name")
.child("user id details")
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot == null || dataSnapshot.getChildrenCount() <= 0) {
goToRegisterDetails(firebaseUser);
return;
}
User user = (User) dataSnapshot.getValue(User.class);
if (user == null
|| user.getUser_name() == null
|| user.getUser_name().isEmpty()
|| user.getUser_mobile() == null
|| user.getUser_mobile().isEmpty()) {
goToRegisterDetails(firebaseUser);
} else {
goToMainActivity(user);
}
}
public void onCancelled(DatabaseError databaseError) {
OTPVerificationActivity.this.hideProgressDialog();
Logger.e(databaseError.getMessage());
}
});
}
I hope that you will get your answer. You can easily achieve that you want to do in your application.
I am developing an app, and so far it's able to upload images, and register users.
However, these two functionalities run independent of each other. Ergo, I need to make it so that the images are saved under the user that uploads it. I am a novice Android programmer and just started learning about Firebase and could use the help.
In Registration process,
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email, email)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
android.util.Log.e("Firebase", "performFirebaseRegistration:onComplete:" + task.isSuccessful());
// 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()) {
AlertUtils.showAlert(MainActivity.this, getString(R.string.sign_up), task.getException().getMessage());
} else {
FirebaseUser firebaseUser = task.getResult().getUser(); // here you will get userDetails
}
}
});
From firebaseUser you can get user id by firebaseUser.getUid().
Once you upload the message,sent to realtime firebase b the user id as below,
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child(ARG_USERS)
.child(firebaseUser.getUid())
.child("image")
.setValue(<you image download url>);