So I'm new to firebase and i have a problem with the method .removeValue(), everytime that method is executed the addOnCompleteListener does not throw any exceptions and execute the .removeValue() method correctly by removing the element but the element keeps adding by itself after the deletion,
I'm trying to do a friend's list where i check the condition if there is a friend request or is the 2 users are actually friends, So i wrote this code on the onStart method to assign the stats variable a value according to these conditions:
#Override
protected void onStart() {
super.onStart();
if(profileUid.equals(userId)){
sendAccept.setVisibility(View.INVISIBLE);
}else {
friendDatabaseReference.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String status = dataSnapshot.child("Status").getValue().toString();
if (status.equals("recieved")) {
sendAccept.setVisibility(View.VISIBLE);
sendAccept.setText("Accept Request");
cancelRequest.setText("Cancel friend Request");
cancelRequest.setVisibility(View.VISIBLE);
stats = "recieved";
} else if (status.equals("sent")) {
stats = "sent";
sendAccept.setText("Cancel Friend Request");
}
} else {
friendDatabaseReference1.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
stats = "friends";
sendAccept.setText("UnFriend");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Everything runs well there and the values are assigned correctly. After that depending of the value of stats these conditions can happen(These sendAccept.setOnClickistener()) is on the onCreate() method:
sendAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (stats.equals("none")) {
friendDatabaseReference.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
friendDatabaseReference.child(userId).child(profileUid).child("Status").setValue("sent").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
friendDatabaseReference.child(profileUid).child(userId).child("Status").setValue("recieved").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
stats = "sent";
sendAccept.setText("Cancel Friend Request");
}
}
});
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else if(stats.equals("recieved")){
friendDatabaseReference1.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
friendDatabaseReference1.child(userId).child(profileUid).child("friends").setValue("yes")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference1.child(profileUid).child(userId).child("friends").setValue("yes")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
stats = "friends";
sendAccept.setText("Unfriend");
cancelRequest.setVisibility(View.INVISIBLE);
friendDatabaseReference.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
friendDatabaseReference.child(profileUid).child(userId)
.removeValue().addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
}
});
}
}
});
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else if(stats.equals("sent")){
friendDatabaseReference.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference.child(profileUid).child(userId).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
stats = "none";
sendAccept.setText("Send Friend Request");
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Asi que prende", Toast.LENGTH_LONG).show();
}
}
});
}
}
});
}else{
friendDatabaseReference1.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference1.child(profileUid).child(userId).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
sendAccept.setText("Send Friend Request");
stats = "none";
}
});
}
}
});
}
}
});
These are my declared instances of FirebaseDatabase where i point out where the data will be or will be removed(these are also on the onCreate() method:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
friendDatabaseReference = FirebaseDatabase.getInstance().getReference().child("friend_req");
friendDatabaseReference1 = FirebaseDatabase.getInstance().getReference().child("Friends");
The conditions don't throw any errors nor exceptions, and all the assigns are working well and finally the firebase deletes the record, but add it again after the deletion
Related
This is the data being inserted the the correct one is the yay#gmail.com while the incorrectly inserted ones are the ones with a:Name
mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Teachers teachers = new Teachers(user, pass, email);
FirebaseDatabase.getInstance().getReference("Teachers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(teachers).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(RegisterTeacher.this, "Teacher has been registered!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(RegisterTeacher.this, TeacherLogin.class);
startActivity(i);
}
else {
Toast.makeText(RegisterTeacher.this, "Failed to register!", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(RegisterTeacher.this, "Failed to register! Try again!", Toast.LENGTH_SHORT).show();
}
}
});
I'm creating a Food ordering app.for that I'm saving the food names into the Food unique ID. So I created Item Details as a node, in this node has shopuniqueID as a child node, in this node has food uniqueID
this ID contains food details such as discount,itemname,price,discount If the User book the foods, which will be saved as below format
, If the customer confirms the food order after that user-selected quantity wants to delete from total item quantity, How can I delete two different values which are in the two different nodes?
This is my tried coding
btnorder=findViewById(R.id.qrbillid);
databaseReference= FirebaseDatabase.getInstance().getReference("User Booking").child(UserID).child(shopid);
dbrefcheck=FirebaseDatabase.getInstance().getReference("Item Details").child(shopid);
btnorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
SelectedItems ui=dataSnapshot1.getValue(SelectedItems.class);
final String itemid=ui.getItemid();
final String Stritemselectedqty=ui.getItemid();
final String name=ui.getItemname();
///////////////////----find the user selection----////////////////////
dbrefcheck.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot2:dataSnapshot.getChildren())
{
UploadItem uploadItem=dataSnapshot2.getValue(UploadItem.class);
String uploadItemID=uploadItem.getKey();
String StrTotalqty=uploadItem.getQuantity();
if(itemid.equals(uploadItemID))
{
// do the mathematical operation
int totalqty=Integer.valueOf(StrTotalqty);
int selectedqty=Integer.valueOf(Stritemselectedqty);
int finalquality=totalqty-selectedqty;
Toast.makeText(MyBookedItems.this, ""+name+" ", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
///////////////////----find the user selection----////////////////////
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
If We want to do mathematical operations between two node child values, We can't directly do that in Firebase Realtime Database.
Retrieve the value from the Firebase
after that do the modification and again upload it.
private void updateQuantity(final String itemid, final String selecteditem) {
Query query4 = dbrefcheck
.orderByChild("key") //key
.equalTo(itemid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String qty=ds.child("quantity").getValue(String.class);
int total=Integer.valueOf(qty);
int sub=Integer.valueOf(selecteditem);
int fv=total-sub;
String sfv=String.valueOf(fv);
Map<String, Object> map = new HashMap<>();
map.put("quantity", sfv);
dbrefcheck.child(itemid).updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
query4.addListenerForSingleValueEvent(valueEventListener);
}
private void moveSelectedItemstoOrder(final DatabaseReference fromPath, final DatabaseReference toPath) {
final String th=toPath.push().getKey();
fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
toPath.child(th).setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
if (firebaseError != null) {
Toast.makeText(MyBookedItems.this, "Try again", Toast.LENGTH_SHORT).show();
} else {
StoreBookingDetails(th);
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void DeleteValuefromSelectedItems() {
databaseReference.setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
private void StoreBookingDetails(final String keytostore) {
//////////////////------------retrive data-------------//////////////////////////////some these methods are unnecessary but i remove some code
savedata(keytostore);
//////////////////------------retrive data-------------//////////////////////////////
}
private void savedata(String keytostore) {
String status="Order Request";
// shopid ---->
BookingDetails bd=new BookingDetails(keytostore,currentdate,UserID,subtotal,status,f1,f2,f3,currentTime);
dbbookingDetails.child(keytostore).setValue(bd).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
DeleteValuefromSelectedItems();
}else
{
Toast.makeText(MyBookedItems.this, "Check the intenet connection", Toast.LENGTH_SHORT).show();
}
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
/////////////////////////////--------------------/////////////////////////////////
UserBookingDetails ubd=new UserBookingDetails(shopname,shopid,shopphnno,keytostore,UserID,subtotal,currentdate,currentTime,"Order Sent","","");
dbbookingdetailsUser.child(keytostore).setValue(ubd).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
AlertDialog.Builder adb = new AlertDialog.Builder(MyBookedItems.this);
adb.setTitle("Booking Successful");
adb.setPositiveButton("View History", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(MyBookedItems.this,OrderHistory.class));
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
adb.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
I was trying to get document id for updating a data, but instead it update all data. How to get document id Firestore?
Code :
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot : task.getResult()) {
String getDocumentID = documentSnapshot.getId();
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").document(getDocumentID).update("inspectorName", inspectorName, "marketLocation", marketLocation).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StartCounting.this, "Document updated", Toast.LENGTH_SHORT).show();
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StartCounting.this, "Error : " + e.toString(), Toast.LENGTH_LONG).show();
progressUpdated.dismiss();
}
});
}
}
}
});
Use set method with SetOptions.merge() to update only required field of document, but if you want to update only one document than don't use update query inside for loop.
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot : task.getResult()) {
String getDocumentID = documentSnapshot.getId();
Map<String, Object> mapUser = new HashMap<>();
mapUser.put("inspectorName", inspectorName);
mapUser.put("marketLocation", marketLocation);
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").document(getDocumentID).set(mapUser, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StartCounting.this, "Document updated", Toast.LENGTH_SHORT).show();
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StartCounting.this, "Error : " + e.toString(), Toast.LENGTH_LONG).show();
progressUpdated.dismiss();
}
});
}
}
}
});
I need to re-authenticate the user in order to delete his profile. I've already seen this answer How to re-authenticate a user on Firebase with Google Provider? but it doesn't work for me. In fact this code below eliminates correctly the user only if he has signed in recently. So in my code seems that user.reauthenticate(credential) doesn't work.
public void OnDeleteProfile(View view){
new AlertDialog.Builder(this)
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
});
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
Please help i want to retrieve a specific data from the Firebase Realtime database I have 2 users Professor and Student and i want to use that data for validations.
FireBase Realtime Database
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
// If the users is professor but if it is student go to userStudent.class
finish();
startActivity(new Intent(getApplicationContext(),userProf.class));
FireBase Realtime Database
This is what you are looking for
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference;
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
reference = FirebaseDatabase.getInstance().
getReference("dbname").child(user.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String usertype=datas.child("user").getValue().toString();
// If the users is professor but if it is
// student go to userStudent.class
if(usertype.equals("Student")){
startActivity(new
Intent(getApplicationContext(),studentProfile.class));
finish();
}else if (usertype.equals("Professor")) {
startActivity(new
Intent(getApplicationContext(),professorProfile.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try this code
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
//user UID
String userId = task.getResult().getUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(userId);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String user = dataSnapshot.child("user").getValue(String.class);
if (user.equals("Student")) {
startActivity(new Intent(getApplicationContext(),userStudent.class));
} else if(user.equals("Professor")) {
startActivity(new Intent(getApplicationContext(),userProf.class));
}
finish();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Hope it helps