How to Delete value from Firebase realtime database by key in android? - android

I have realtime database in firebase it look like this
Now I want to delete value by key in android (java).
I have tried this code
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("coating").child("88").removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(activity, "on success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(activity, "on success"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I get success response in onSuccess Method but value in database is not deleted.

As per this document
check out last para about delete and update ui

Related

Not able to commit data into realtime database of firebase

I'm trying to add the data entered by the user into the realtime database, but it stops working and doesn't commit data. The image gets stored in the firebase storage, but data isn't getting saved in realtime and the activity closes and moves back to the previous activity.
This the code in the activity file:
pst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final StorageReference reference = storage.getReference().child("compan")
.child(compName.getText().toString())
.child(new Date().getTime()+"");
reference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(addPost.this, "Post added", Toast.LENGTH_SHORT).show();
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
postModel po = new postModel();
po.setPostImg(uri.toString());
po.setPostedBy(FirebaseAuth.getInstance().getUid());
po.setPostDescr(descrip.getText().toString());
po.setPostId(new Date().getTime()+"");
database.getReference().child("Company").child(compName.getText().toString())
.push()
.setValue(po).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(addPost.this, "Post added", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
});
On trying a lot I got the following error in the logcat:
enter image description here
Am I missing something? I don't know what to do as the storage and authentication works fine.
Please check the database object, it seems it hasn't been initialized before using:
database = ... // initialize somehow
database.getReference().child("Company").child(compName.getText().toString())
...

How to remove two documents in Firebase cloud database?

I wrote the following code that deletes two documents from the cloud Firebase database:
fireDB.document(groupPath).collection("users").document(phoneNumber).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
fireDB.collection("users").document(phoneNumber).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(this.getClass().getName(), "DocumentSnapshot successfully deleted");
Toast.makeText(getApplicationContext(),R.string.successfully_deleted_user,Toast.LENGTH_LONG).show();
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(this.getClass().getName(), "Error deleting document", e);
Toast.makeText(getApplicationContext(),R.string.failed_to_delete_user,Toast.LENGTH_LONG).show();
}
});
Log.d(this.getClass().getName(), "DocumentSnapshot successfully deleted");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(this.getClass().getName(), "Error deleting document", e);
Toast.makeText(getApplicationContext(),R.string.failed_to_delete_user,Toast.LENGTH_SHORT).show();
}
});
The problem with that code is that it deletes first document and then deletes second document, meaning if the first try will delete it successfully and the second one will fail to delete it, there is going to be a problem. Is it possible to delete two documents in Firebase cloud database so the result could be of of the following two options:
Both of the documents are deleted.
Both of the document are not deleted.
Is it possible to do?
As robsiemb commented, you'll want to use a batch write or transaction for this.
As far as I can see, the equivalent from your code would be something like this:
// Get a new write batch
WriteBatch batch = db.batch();
DocumentReference docRef1 = fireDB.document(groupPath).collection("users").document(phoneNumber);
DocumentReference docRef2 = fireDB.collection("users").document(phoneNumber)
DocumentReference laRef = db.collection("cities").document("LA");
batch.delete(docRef1);
batch.delete(docRef2);
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});

Checking for a string in firestore always returns true

I am new to android development and firestore. What I am trying to do is compare whether a string exists in the database or not. However, the query always returns true even if I am trying to compare with string that is not present in the database. Here is my code:
public void loadData(View v){
db.collection("Machines")
.whereEqualTo("machineId","AYSLE004")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
//MachineId exists
Toast.makeText(MainActivity.this, "Machine Id exists", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//Machine Id does not exist
Toast.makeText(MainActivity.this, "Machine Id does not exist", Toast.LENGTH_LONG).show();
Log.d(TAG,e.toString());
}
});
}
The string "AYSLE004" does not exist in the database. However the toast message shows "Machine Id exists". Please assist me where I am going wrong. Thanks in advance.
Try adding the following:
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
//MachineId exists
if(queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
Toast.makeText(MainActivity.this, "Machine Id exists", Toast.LENGTH_LONG).show();
} else {
//it doesn't exist
}
}
}
The reason for this (I believe) is because the onSuccess listener is called because the request to Firebase was completed and achieved successfully, it just didn't happen to find your request.

How to avoid NullPointerException when deleting a document in Firestore?

I want to give the user in my app the possibility to delete his account so when he clicks on the delete button a document gets deleted which contains all his informations. The name of the document is his displayName so I get this as a string but when I run the code you are seeing below I get a NullpointerException in this line:
String currentUsername = user.getDisplayName();
even though the displayName is not null.
Edit:
I found the solution on my own, see the answer below.
Here is my method:
btn_delete_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
deleteDocument();
}
}
});
}
});
...
public void deleteDocument (){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String currentUsername = user.getDisplayName();
db.collection("User").document(currentUsername)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
Toast.makeText(PersonalSettings.this, "Your account was successfully deleted.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
startActivity(i);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
First thing you have to check that current user is not null
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null)
{
return;
}
if current user is not null then get its name and further check that it's name is not null.
String currentUsername = user.getDisplayName();
if(TextUtils.isEmpty(currentUsername))
{
return;
}
if name is not null then go for delete document as follows :
public void deleteDocument (){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null)
{
return;
}
String currentUsername = user.getDisplayName();
if(TextUtils.isEmpty(currentUsername))
{
return;
}
db.collection("User").document(currentUsername)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
Toast.makeText(PersonalSettings.this, "Dein Account wurde erfolgreich gelöscht.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
startActivity(i);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
I think you're misunderstanding the error. It's saying that user is null, not the display name. This means there is currently no user signed into the app. You will have to write some code to check for this case.
I also strongly suggest not using a display name as the ID for a document in Cloud Firestore. Since you're using Firebase Authentication, the user already has a unique ID assigned to their account. This is the preferred way to store per-user data.
I found the error:
I called my delete method after I used the user.delete() method which deletes the signed in user, so logically the displayName was also deleted.

Can't delete node from FirebaseDatabase using removeValue()

I try to delete a node from my FirebaseDatabase with removeValue() but it doesn't work .The strange thing is that when i delete it inside Recyclerview the node deleted successfully .
I pass the ref from Recyclerview with onclick in a new Activity using the code below .
final DatabaseReference itemRef = getRef(position);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// itemRef.removeValue();
Intent intentshowall2one= new Intent(Showcase.this, ShowProduct.class);
intentshowall2one.putExtra("S2Skey", itemRef.toString());
Showcase.this.startActivity(intentshowall2one);
and on the other activity
key = myIntent.getStringExtra("S2Skey");
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl(key);
mDatabase.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Make sure you have given proper reference before you remove a value. then,
you can use Completion listener instead of OnSuccessListener, Completion listener gives accurate result.
Try this out in Your Button or any Listener :
mDatabase.child(key).removeValue();
Toast.makeText(getApplicationContext(),"The Post has been removed Successfully ",Toast.LENGTH_LONG).show();
Or use this
mDatabase.chlid(key).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Instead of :
mDatabase.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Hope it works for You
Thanks for your answers Lutaaya Huzaifah Idris and Vignesh Kumar.I found out that the error was because i was using Greek words inside my path.Everything worked fine upload download and query the ref with Greek words but when i passing the ref to the other activity the ref changed .That is also strange.

Categories

Resources