setValue() not working in firebase realtime database - android

I'm trying to create new data in the firebase realtime database
I tried to use a HashMap and an object, none of them works.
even when I put the OnComplete/OnSuccess/OnFailure listeners I don't receive any data in the log.
private void registerUser(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser currentUser = mAuth.getCurrentUser();
String uid = currentUser.getUid();
HashMap<String, String> userMap = new HashMap<>();
User user = new User(displayName, "Bonjour!", "par defaut", "def");
userMap.put("name", displayName);
userMap.put("status", "Bonjour!_Je_viens_de_m'inscirire");
userMap.put("image", "par_defaut");
userMap.put("thumb_image", "def");
Log.d(TAG, "onComplete: " + userMap);
Log.d(TAG, "onComplete: " + user);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(uid);
mDatabaseReference.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: ");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
Log.d(TAG, "onComplete: " + mDatabaseReference);
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mRegProgressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, "impossible d'inscrire, veuillez ressayer!", Toast.LENGTH_LONG).show();
}
I tried adding this code and it gives me :" not connected " in the log.
//check if connected
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
Log.d(TAG, "connected");
} else {
Log.d(TAG, "not connected");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.w(TAG, "Listener was cancelled");
}
});
the HashMap contains the actual data but the setValue() method does not work for some reason. When I look in the firebase console there are no changes.

the code responsible for changing the activity from RegisterActivity to MainActivity ran before actually being able to send the data to the database.
to solve the problem I just put the part of the code responsible for changing the activity and all that:
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
inside the OnSuccessListener.
so the final code is:
private void registerUser(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser currentUser = mAuth.getCurrentUser();
String uid = currentUser.getUid();
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", displayName);
userMap.put("status", "Bonjour!_Je_viens_de_m'inscirire");
userMap.put("image", "par_defaut");
userMap.put("thumb_image", "def");
mDatabaseReference = mDatabase.getReference("Users").child(uid);
mDatabaseReference.setValue(userMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: ");
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mRegProgressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, "impossible d'inscrire, veuillez ressayer!", Toast.LENGTH_LONG).show();
}
}
});
thanks for the commenters.

Related

E Failed to getEnergyData

I wanna register a user in firebase firestore but when I click the register button nothing happens. I don't understand where I went wrong . It doesn't even create the user or send the data to the database
fStore = FirebaseFirestore.getInstance();
signi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mail = regemail.getText().toString().trim();
String pin = pass.getText().toString().trim();
String confarm = confir.getText().toString().trim();
String phon = tele.getText().toString().trim();
fAuth.createUserWithEmailAndPassword(mail, pin).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(registrations.this, "Registration Successful", Toast.LENGTH_SHORT).show();
Map<String, Object> user = new HashMap<>();
user.put("Email", mail);
user.put("Password", pin);
user.put("Phone", phon);
df.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
startActivity(new Intent(registrations.this, login.class));
}
else {
Toast.makeText(registrations.this, "Registration Failed!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();```
It was working before. I was able to create user and sign in but moving that data to the database is the problem. Also I had used realtime database before and it worked but it was overwtiting the data in the database when I tried to register a new user so I decided to use firestore instead

Calling too many firebase function in one method

I'm currently making a method that allows current logged in user to sign up a new user and add them into as their downline friends using firebase. And while i was developing this method i realise that I've been bloating too much firebase functions into one method and i believe this would cause trouble when something is wrong with the inner function.
private void ValidateAccount(final String name, final String phone,final String email,
final String password, final String confirmPassword,
final String points,
final DatabaseReference RootRef, final FirebaseAuth firebaseAuth) {
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
final FirebaseUser userkey = firebaseAuth.getCurrentUser();
final String userkeyString = userkey.getUid();
RootRef.child(userkeyString)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!(dataSnapshot.exists())){
HashMap<String, Object> userDatamap = new HashMap<>();
final HashMap<String, Object> currentUserDatamap = new HashMap<>();
userDatamap.put("id",userkeyString);
userDatamap.put("phone",phone);
userDatamap.put("name",name);
userDatamap.put("email",email);
userDatamap.put("upline", upline);
addNewDownline(userkeyString);
currentUserDatamap.put("downlines", downlinesMaps);
RootRef.child(userkeyString).updateChildren(userDatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
RootRef.child(currentUser.getId()).updateChildren(currentUserDatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterDownlineActivity.this, "Congratulations your account has been created.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
firebaseAuth.signOut();
Intent intent = new Intent(RegisterDownlineActivity.this, HomeActivity.class);
startActivity(intent);
}
else{
loadingBar.dismiss();
Toast.makeText(RegisterDownlineActivity.this, "Network Error: Please try again.", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else{
Toast.makeText(RegisterDownlineActivity.this,"The username already belong to someone else.",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
Toast.makeText(RegisterDownlineActivity.this, "Please try again using another username.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterDownlineActivity.this, MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(RegisterDownlineActivity.this, "System Error. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
else{
Log.d( "FAIL", String.valueOf(task.getException()));
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed."+String.valueOf(task.getResult()),
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
try{
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed: Email is already being used",
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
catch (RuntimeExecutionException task){
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed: Email is already being used",
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
For example, if something is wrong with the updateChildren() then the method will show failure at the updateChildren() part, but the createUserWithEmailAndPassword() will still execute.
What i wish to achieve is that whenever there's an error in the function all the function will not execute and shows the error.
If createUserWithEmailAndPassword() executed and updateChildren() failed, then inside .addOnFailureListener you can delete the user:
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete();
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});

Verify if a User is new or already exists Android Studio [duplicate]

This question already has an answer here:
Users info are re-initialized after logging out and signing in
(1 answer)
Closed 4 years ago.
i am working on a application and i use firebase for user login authentication and everything works perfect. Recently i thought of a new idea for the app and i would like to check if a user exists or if its the first time. if its the first time the user goes to a new activity and if the user exists it goes to the home activity. i tried documentations and i didn't really understand. Can someone help me with code sample or better explanation.
this is the login code
private void user_login(String email, String password) {
if (email.isEmpty()){
emailtx.setError("email is empty");
emailtx.requestFocus();
}
if (password.isEmpty()){
passwordtx.setError("password is empty");
passwordtx.requestFocus();
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
emailtx.setError("Please enter a valid email");
emailtx.requestFocus();
return;
}
if (password.length()< 6){
passwordtx.setError("password is short");
passwordtx.requestFocus();
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String user_id = current_user.getUid();
String device_token = FirebaseInstanceId.getInstance().getToken();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("image", "https://firebasestorage.googleapis.com/v0/b/bookshare-8e018.appspot.com/o/male.png?alt=media&token=60cbb24c-b9f9-4724-b8bf-69a76386fcca");
userMap.put("thumb_image", "default");
userMap.put("device_token", device_token);
userMap.put("home", "earth");
userMap.put("work", "earth");
userMap.put("others", "earth");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent mainIntent = new Intent(login.this, selectestado.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
});
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
below mDatabase you can check if the user exists
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
HashMap<String, String> userMap = new HashMap<>();
userMap.put("image", "https://firebasestorage.googleapis.com/v0/b/bookshare-8e018.appspot.com/o/male.png?alt=media&token=60cbb24c-b9f9-4724-b8bf-69a76386fcca");
userMap.put("thumb_image", "default");
userMap.put("device_token", device_token);
userMap.put("home", "earth");
userMap.put("work", "earth");
userMap.put("others", "earth");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent mainIntent = new Intent(login.this, selectestado.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
});
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
}else{
//User does not exists
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});

I am trying to add data to my firebase database by using cloud firestore but it is not adding data neither is it showing any errors

This is the method in which new user get's registered and after registering I use the user ID to add the user data to the database:
public void registerNewEmail(final String email, String password, final TextInputLayout mEmailInputTextLayout, final TextInputLayout mPasswordInputLayout, final String firstName, final String lastName){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(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, "register user : starting ");
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
assert user != null;
userID = user.getUid();
Log.d(TAG, "UserID: " + userID);
Toast.makeText(mContext,"Sign Up was Successful", Toast.LENGTH_SHORT).show();
sendVerificationEmail();
addNewUser(firstName, lastName, email, userID);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
if(task.getException() instanceof FirebaseAuthUserCollisionException){
mEmailInputTextLayout.setError(mContext.getString(R.string.email_already_used_error));
}
if(task.getException() instanceof FirebaseAuthWeakPasswordException){
mPasswordInputLayout.setError(mContext.getString(R.string.weak_password));
}
mProgressBar.setVisibility(View.GONE);
}
}
});
}
This is the method in which I have used firestore reference to add the data to the firebase database:
/*
* Add new usser to Database
* */
private void addNewUser(String firstName,String lastName,String email,String userID){
String name = firstName + " " + lastName;
User user = new User(name,email);
Log.d(TAG, "addNewUser: " + "userID: " + userID);
mRef.collection(mContext.getString(R.string.DB_users)).document(userID).set(user);
mAuth.signOut();
((Activity)mContext).finish();
}
You can replace mRef.collection(mContext.getString(R.string.DB_users)).document(userID).set(user); with:
db.collection(mContext.getString(R.string.DB_users)).document(userID)
.set(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});

SignOut is making not possible to save in firestore

I'm making a signup activity for an app and something weird is happening can you help me?
this is the code for signup some on and it works if I comment the signOut function but I need it to signout after saving the data in the FirebaseAuth and the Firestore.
I don't get even the logs.
public void registUser() {
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(user.getEmail(), user.getPassword()).addOnCompleteListener(SignUpUserActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpUserActivity.this, "Sucesso", Toast.LENGTH_SHORT).show();
// Sign in success, update UI with the signed-in user's information
//FirebaseUser user = mAuth.getCurrentUser();
user.setId(task.getResult().getUser().getUid());
user.save();
mAuth.signOut();
finish();
} else {
String erro = "";
try {
throw task.getException();
} catch (FirebaseAuthWeakPasswordException e) {
erro = "Digite uma senha mais forte";
} catch (FirebaseAuthInvalidCredentialsException e) {
erro = "Email invalido";
} catch (FirebaseAuthUserCollisionException e) {
erro = "Email Registado";
} catch (Exception e) {
erro = "Erro generico";
e.printStackTrace();
}
Toast.makeText(SignUpUserActivity.this, erro, Toast.LENGTH_SHORT).show();
}
}
});
}
I think its because it takes to long to save things in the database.
I have no problems with the Auth part.
Thank you.
this is the save function.
public void save(){
DocumentReference reference = FirebaseFirestore.getInstance().document("/Clinicas/" + clinic + "/Profissionais/" + id + "/");
Map<String, Object> dataToSave = new HashMap<String, Object>();
dataToSave.put("Name", name);
dataToSave.put("email", email);
dataToSave.put("clinic", clinic);
dataToSave.put("Job", job);
reference.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("artur", "Saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("artur", "Not Saved",e);
}
});
}
To sovle this, please use the following code:
user.setId(task.getResult().getUser().getUid());
userRef.set(user).addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
mAuth.signOut();
}
});
When you sign-out, you need to be sure that your write operation is done and this can only be achieved using addOnSuccessListener.
public void save(){
DocumentReference reference = FirebaseFirestore.getInstance().document("/Clinicas/" + clinic + "/Profissionais/" + id + "/");
Map<String, Object> dataToSave = new HashMap<String, Object>();
dataToSave.put("Name", name);
dataToSave.put("email", email);
dataToSave.put("clinic", clinic);
dataToSave.put("Job", job);
reference.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("artur", "Saved");
mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("artur", "Not Saved",e);
}
});
}

Categories

Resources