My FireBase Database doesn't save information - android

I am working on my project and I need save information about my users. I chose Realtime Database, but it doesnt work. I have an exception:
This email is already in use
through I insert new email. I use everything(google.json, SHA-1, SHA-256), but my signing up new users doesnt work correctly. My rules:
{
"rules": {
".read": true,
".write": true
}
}
My class Person:
public String name, email;
public User(){}
public User(String name, String email){
this.name = name;
this.email = email;
}
}
My FireBaseAuth, FireBaseDataBase:
private FirebaseAuth mAuth;
private FirebaseDatabase usersDataBase;
///
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
User user = new User(username, email);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterActivity.this, "Пользователь успешно добавлен", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, SigningActivity.class));
}
else{
Toast.makeText(RegisterActivity.this, "Произошла ошибка! Пожалуйста, попробуйте позже", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});

Related

firebase google and phone number signup user every time

I used firebase phone and google authentication in my app I am facing an issue that when a user logout and signing again though OTP or google it signup the user again by creating new user id and all the information that user update through profile update option erased and come back in original state as new user and all updates of profile lost.
My phone sign in code is here
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber)
.setTimeout(120L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String verifyId, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(verifyId, forceResendingToken);
verificationId = verifyId;
}
}).build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
public void callNextScreen(View view) {
dialog.show();
String otp = binding.otpView.getText().toString();
if (otp!= null) {
verifyOTP(otp);
} else {
Toast.makeText(this, "Enter code", Toast.LENGTH_LONG).show();
}
}
private void verifyOTP(String otp) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, otp);
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String uid = auth.getCurrentUser().getUid();
String phoneNumber = auth.getCurrentUser().getPhoneNumber();
User users = new User();
users.setPhone(phoneNumber);
database
.collection("users")
.document(uid)
.set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
dialog.dismiss();
Intent intent = new Intent(OTP_Activity.this, MainActivity.class);
startActivity(intent);
finishAffinity();
} else {
dialog.dismiss();
Toast.makeText(OTP_Activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
dialog.dismiss();
Toast.makeText(OTP_Activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
and my user attributes and user class constructor looks like this
private String name, email, image, phone, gender;
private long coins = 500;
public User(String name, String email, String image, String phone, String gender) {
this.name = name;
this.email = email;
this.image = image;
this.phone = phone;
this.gender = gender;
}
public User() {
}
this is how creating user profile with google signing
private void firebaseAuthWithGoogle(String idToken){
AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null);
auth.signInWithCredential(firebaseCredential)
.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("TAG", "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
String uid = user.getUid();
User newUser = new User();
newUser.setName(user.getDisplayName());
newUser.setEmail(user.getEmail());
newUser.setImage(user.getPhotoUrl().toString());
database
.collection("users")
.document(uid)
.set(newUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
dialog.dismiss();
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
finishAffinity();
} else {
dialog.dismiss();
Log.w("TAG", "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
dialog.dismiss();
// If sign in fails, display a message to the user.
Toast.makeText(SignupActivity.this, "Signup Failed", Toast.LENGTH_SHORT).show();
// updateUI(null);
}
}
});
}

How to create a account with Email And Password method after Verifying Phone with PhoneAuthProvider?

I am working on a kind of shopping Android app and at the time of creating new user account i want to verify the user with his Phone number and want to log in the user by there email.
PhoneAuthProvider.getInstance().verifyPhoneNumber(users.getPhoneNumber(), 120, TimeUnit.SECONDS, Otp_Activity.this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull #NotNull String s, #NonNull #NotNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
otpID = s;
progressDialog.dismiss();
Toast.makeText(Otp_Activity.this, "Otp sent", Toast.LENGTH_SHORT).show();
}
#Override
public void onVerificationCompleted(#NonNull #NotNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull #NotNull FirebaseException e) {
Toast.makeText(Otp_Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth = SplashScreen.firebaseAuthForPhone;
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
Toast.makeText(Otp_Activity.this, "Account Created", Toast.LENGTH_SHORT).show();
createAccountWithEmail(userEmail, userPassword);
}
else
{
Toast.makeText(Otp_Activity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void createAccountWithEmail(String email, String passWord)
{
firebaseAuthForEmail.createUserWithEmailAndPassword(email, passWord)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
firebaseAuth.signOut();
Toast.makeText(Otp_Activity.this, "Email Account Created", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(Otp_Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Why i cant logout with the account created with email?
do PhoneAuthProvider logs in after verifying account? if yes is there any way to stop it?
You could use one specific authentication process for each user. If you need to authenticate the user with the email and password, follow this process.
private FirebaseAuth mAuth;
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
Then create account with email and password.
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// add the logic
} else {
// add the logic
}
}
});
After account creating process, you could use this process for the sign in process.
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// add the logic
} else {
// add the logic
}
}
});
And you could use this method for sign out the user.
FirebaseAuth.getInstance().signOut();

User is created but data is not stored in Firebase realtime database

I have created a simple signup form. When I click signup, the user gets created but the data, such as name and email is not saved in a real-time database. I have tried and tested everything I could find online. My real-time database server is ASIA SOUTH-EAST1. And I have also changed the rules to true.
Below is my code to create user:
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
User muser= new User(name, email);
//user is created and can be seen in authentication list
//Code down below is to add data to database but doesnt work!
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(muser)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(Signup_User.this, "Registered successfully!
PLEASE LOGIN AGAIN", Toast.LENGTH_LONG).show();
startActivity(new Intent(Signup_User.this,
Home_activity.class));
progressBar.setVisibility(View.GONE);
}else{
Toast.makeText(Signup_User.this, "Something went wrong!",
Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}else{
Toast.makeText(Signup_User.this, "Failed to register, Something went
wrong!" + task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
And the User.java file:
package com.example.covoid;
public class User {
public String name, email;
public User(){
}
public User(String name, String email){
this.name = name;
this.email = email;
}
}
Did you uninstall and install the app again?
That is essential for the communication with FireBase.

How to add username with FirebaseAuth in android

Firebase register code is given below. When I add username as a parameter, the method does not let me do it.
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if(task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
//display some message here
Toast.makeText(RegisterActivity.this,"Bir hata oldu",Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
you need to update user after creating it.
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(YourActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
} else {
addUserNameToUser(task.getResult().getUser());
}
}
)};
private void addUserNameToUser(User user){
String username = "username";
String email = user.getEmail();
String userId = user.getUid();
User user = new User(username, email);
firebaseDB.child("users").child(userId).setValue(user);
}
the variable firebaseDB should be created before. You can create in where you create firebaseAuth like so ;
firebaseDB = FirebaseDatabase.getInstance().getReference();
Update 1
using com.google.firebase:firebase-auth:11.6.2
public class MainActivity extends AppCompatActivity {
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.createUserWithEmailAndPassword("erginersoyy#gmail.com", "12345").addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
} else {
addUserNameToUser(task.getResult().getUser());
}
}
});
}
private void addUserNameToUser(FirebaseUser user) {
String username = "username";
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
}
}
you can also check this link

Firebase login and signup with username

I am currently using AndroidHive's tutorial to learn how to use Firebase, I am starting to understand the methods and documentation well now - I realised that Firebase offers a signup/sign-in method with email and password, and that this piece of information is not stored in our database.
I would like to implement a system where when they sign up they provide their email,password and a username along with some other data and it all gets saved to the database. So that the user can then signin with their email or username. I found this article on stack which apparently is the answer to this question I am asking - However, I do not fully understand this and how it links with my code below
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
Any help is much appreciated thanks
Try this:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
generateUser(email, password)
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
This is the method that is being called above.
public void generateUser(String username, String password)
{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference users = database.getReference("users"); //users is a node in your Firebase Database.
User user = new User(username, password); //ObjectClass for Users
users.push().setValue(user);
}
Also:
User.class
public class User {
String username;
String password;
public User() {
//Empty Constructor For Firebase
}
public User(String username, String password)
{
this.username = username; //Parameterized for Program-Inhouse objects.
this.password = password;
}
//Getters and Setters
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
Undo the addition of .getDatabase(); first.
This is not a native Firebase method, my mistake.
I got your problem.
Make FirebaseDatabase a global variable and initialise it in onCreate. It requires a context at the point.
Just take FirebaseDatabase database; before onCreate.
And In, onCreate: initialise, database=FirebaseDatabase.getInstance();.
Don't initialise in method. I'll edit my previous answer soon.

Categories

Resources