API callback not getting called with FireStore - android

I have following method which i call, but i dont see any call back getting called.
Log.d(TAG,"adding to firebase");
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "rambo");
user.put("last", "Lovelace");
user.put("born", 1815);
db.collection("aks")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(FIRE_TAG, "akshay:DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(FIRE_TAG, "akshay:Error adding document", e);
}
})
.addOnCanceledListener(new OnCanceledListener() {
#Override
public void onCanceled() {
Log.w(FIRE_TAG,"akshayoncancel listner");
}
})
.addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
Log.w(FIRE_TAG,"on completed listner");
}
});
Log.d(TAG,"done");
I see that "adding to firebase" and "done" printed on console, but nothing success/failure callbacks are not getting called. Why so?

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

In what circumstances does Firebase trigger OnCanceled()

I would like to cover all cases of failure in firebase/firestore. I've seen functions trigger OnFailure callback, but under what circumstances does OnCanceled get triggered? I haven't been able to force any triggers of OnCanceled() for a variety of functions such as writes/deletes as well as operations on FirebaseUser and AuthUI and haven't seen any documentation. Are these cases documented somewhere?
FirebaseDatabase.getInstance().getReference("users/test").setValue("blabla")
.addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Log.v("TEST", "DB WRITE SUCCESS");
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Log.v("TEST", "DB WRITE FAILURE " + e);
}
})
.addOnCanceledListener(new OnCanceledListener()
{
#Override
public void onCanceled()
{
Log.v("TEST", "DB WRITE CANCELLED");
}
});
FirebaseFirestore fs = FirebaseFirestore.getInstance();
fs.collection("users").document("blabla").set(data)
.addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Log.v("TEST", "FS WRITE SUCCESS");
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Log.v("TEST", "FS WRITE FAILURE " + e);
}
})
.addOnCanceledListener(new OnCanceledListener()
{
#Override
public void onCanceled()
{
Log.v("TEST", "FS WRITE CANCELLED");
}
});
FirebaseUser user = mAuth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.build();
user.updateProfile(profileUpdates)
.addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Log.v("NICK", "SUCCESS UPDATED PROFILE");
}
})
.addOnCanceledListener(new OnCanceledListener()
{
#Override
public void onCanceled()
{
Log.w("NICK", "CANCELED UPDATE PROFILE");
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Log.w("NICK", "FAILED TO UPDATE PROFILE");
}
});
AuthUI.getInstance().delete(this)
.addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Log.v("AUTHUI", "SUCCESS DELETED ACCNT");
}
})
.addOnCanceledListener(new OnCanceledListener()
{
#Override
public void onCanceled()
{
Log.w("AUTHUI", "CANCELED DELETE ACCNT");
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Log.w("AUTHUI", "FAILED TO DELETE ACCNT " + e);
}
});
under what circumstances does OnCanceled get triggered?
It doesn't. Task cancelation only happens for tasks that are specifically designed to be cancelable. That doesn't happen to Firestore tasks.

Get and delete all documents in a Firestore subcollection

I want to get and delete all the documents in a subcollection called "journal" but it doesn't work and did not show any toast message or errors.
It would be very helpful if someone tells me what is wrong. Thank you a lot.
This is the code I use to get and delete all the documents in a subcollection:
final String userid = FirebaseAuth.getInstance.getCurrentUser().getUid();
FirebaseFirestore. getInstance().collection("main").document(userid).collection("journal").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (final QueryDocumentSnapshot document : task.getResult()) {
db.collection("main").document(userid).collection("journal").document(document.getId()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(SettingsActivity.this, "Deleted: " + document.getId(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SettingsActivity.this, "error getting: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
Firestore structure :
collection(main) ---> document(userid)---> collection(journal)---> document 1
---> document 2
--> document 3
Try this.
final String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore.getInstance().collection("main").document(userid).collection("journal").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot document: queryDocumentSnapshots.getDocuments()) {
db.collection("main").document(userid).collection("journal").document(document.getId()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(SettingsActivity.this, "Deleted: " + document.getId(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
});
Also, please make sure you have set your db rules to allow delete event

firestore keep updating in infinite loop

I just want to update the count table one time but it keeps updating in the infinite loop can someone help me with this.
referral_code=referral_editText.getText().toString();
db.collection(REFERRAL_CODE_KEY).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
assert queryDocumentSnapshots != null;
for(DocumentSnapshot documentSnapshots:queryDocumentSnapshots){
if(referral_code.equals(documentSnapshots.get(REFERRAL_CODE).toString()))
{
count = parseInt(String.valueOf(documentSnapshots.get(REFERRAL_COUNT)))+1;
Map<String, Object> referralCountDocData = new HashMap<>();
referralCountDocData.put(REFERRAL_COUNT,count);
klog.d("### referral",count+"");
db.collection(REFERRAL_CODE_KEY)
.document(documentSnapshots.getId())
.update(referralCountDocData).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
finish();
}
});
}
}
}
});
Maybe, you could do something like this not everythng is perfect but it gives you a nice idea.
oldCount-> you can read it from document.getData()
var docRef = db.collection(REFERRAL_CODE_KEY).doc(referral_code);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
//read oldCount here from document.getData()
Map<String, Object> docData= new HashMap<>();
docData.put(REFERRAL_COUNT, oldcount + 1);
docRef.set(docData)
.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);
}
});
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
You can detach your listener, so that callback stop getting called.
As per official document https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener You need to use remove method to detach listener
Query query = db.collection("cities");
ListenerRegistration registration = query.addSnapshotListener(
new EventListener<QuerySnapshot>() {
// ...
});
// ...
// Stop listening to changes
registration.remove();

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