So I have a collection in Cloud Firestore which I populate by clicking some buttons in my application. Once I close the app, I want the collection to be empty. Is there any way I can do that? I tried to implement onStop() method, but it does nothing.
protected void onStop() {
super.onStop();
db.collection("AddPlaces").document()
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("SUCCES", "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("FAILURE", "Error deleting document", e);
}
});
}
Any ideas if I can achieve that?
An empty collection means a collection with no documents. If you want to delete all documents in a collection, I recommend you see my answer in the following post:
How delete a collection or subcollection from Firestore?
Why your code is not working? Is because of the following line of code:
db.collection("AddPlaces").document()
Which basically generates a document with a random ID, and nothing more. So when you call delete(), you're trying to delete a single document and not all documents in the collection, hence that behavior.
One more thing to note is that if you delete all documents in the collection, that collection will not exist anymore. It will exist again when you'll write a new document in it.
Related
I'm trying to make a social media application with firebase in android studio, now my application is finished, it works smoothly, but there is a problem, there is a delete button on the shared post, when this button is clicked, I want it to delete only that selected picture.
Can you help me, please?
if you're asking about firebase database you can do something like
// Reference to the node you want to delete
DatabaseReference postRef = FirebaseDatabase.getInstance().getReference("posts").child(postId);
// Delete the node
postRef.removeValue();
in case you are talking about firebase storage you can do something like
// Reference to the image you want to delete
StorageReference imageRef = storageRef.child("images/myimage.jpg");
// Delete the image
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
}
});
you must include the dependency in build.gradle
implementation 'com.google.firebase:firebase-storage:19.2.0'
sorry i didn't had enough reputation here to comment and ask so directly posting an answer
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(itemsAdapter);
registerForContextMenu(listView);
fstore.child(/*MyFolder1*/).child(/*MyFolder2*/).listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult listResult) {
for(StorageReference sref : listResult.getItems())
{
items.add(sref.getName()); //<- NOT working
System.out.println("IIIIII: "+sref.getName()); //sref.getName() returns proper value here
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(tabtwoactivity.this, "Fetching failed", Toast.LENGTH_LONG).show();
}
});
itemsAdapter.notifyDataSetChanged();
Why doesn't sref.getName() get added to the list? All items.add() statements before and after work properly.
Ignore this part - I need to add some more info to be able to publish the question. I hope this much is enough.
The Firebase Storage API listAll() is asynchronous and returns immediately before the results are available. Your callback is invoked some time later, after the results are available. While listAll() is executing, your code does on to immediately render the empty list, and notifyDataSetChanged ends up doing nothing. Your code needs wait for the results to complete before trying to render any views.
Try instead calling itemsAdapter.notifyDataSetChanged() from within the onSuccess callback to force the adapter to render the new results.
fstore.child(/*MyFolder1*/).child(/*MyFolder2*/).listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult listResult) {
for(StorageReference sref : listResult.getItems())
{
items.add(sref.getName()); //<- NOT working
System.out.println("IIIIII: "+sref.getName()); //sref.getName() returns proper value here
}
itemsAdapter.notifyDataSetChanged();
}
You will probably also want to decide what you want to display before listAll() is complete, as it might not be as fast as you want.
In my TimeForm activity I add some data to Firestore but I don't add them in specific documents because I need to read them all using .addSnapshotListener
But I need to delete some of the documents. For example here are my documents in the Monday collection:
But when I tried to delete them doing this:
db.collection("monday").document()
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
It doesn't work because I haven't set the document name. Then I asked how to get a documents id(here is the page: Delete data from firestore) it didn't send the correct document id. I added a test button and when I clicked it, it displayed a toast with the document's id but everytime I pressed it, it displayed random ids and none of them were correct. How can I delete those documents one by one of all of them at once.
it displayed random ids and none of them were correct.
This is happening because you aren't passing anything to the document() method. According to the official documentation of CollectionReference's document() method:
Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.
So everytime you call document() method without passing any argument, you get a new auto-generated ID which will never match with one of your existing one.
In order to delete a particular document, you need to pass the particular id of the document that you want to delete to the document() method. It might look something like this:
db.collection("monday").document("2wZg ... GmfS").delete().addOnSuccessListener(/* ... */);
I'm using Firestore in my app and I can't figure out how to handle at user level the exceptions thrown by that. (I mean what to display to the user when such exceptions occur).
For example, to perform any CRUD operation on Firestore (DocumentReference#get, DocumentReference#set, DocumentReference#update) a Task is returned, which might contain an exception, but in the documentation I can't find why this exception might be thrown by Firestore.
Is there something better that we can do, rather than simply log the exception and show a generic message like "an error occurred, please try again later"?
As in the official documentation regarding getting data, you can get the exception from the task object like this:
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());
} else {
Log.d(TAG, "No such document");
}
} else {
//Log the error if the task is not successful
Log.d(TAG, "get failed with ", task.getException());
}
}
});
And remember, a Task is complete when the work represented by the Task is finished, regardless of its success or failure. There may or may not have been an error, and you have to check for that. On the orter side, a Task is "successful" when the work represented by the task is finished, as expected, with no errors.
As #Raj mentioned in his answer, you can also use addOnFailureListener but note, if there is a loss of network connectivity (there is no network connection on user device), neither onSuccess() nor onFailure() are triggered. This behavior makes sense, since the task is only considered completed when the data has been committed (or rejected) on the Firebase server. onComplete(Task<T> task) method is called also only when the Task completes. So in case of no internet connection, neither onComplete is triggered.
You can use onFailureListener() method of Firestore and get the errors while getting, setting or updating the data. In this example I have used it in setting data:-
firestore.collection("User").document(uid).set(user).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid)
{
//Data Saved Successfully
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(Exception e)
{
//Toast error using method -> e.getMessage()
}
});
If you want to catch exceptions in firebase authentication module then refer:- How to catch a Firebase Auth specific exceptions
Hi i seem to be forever looking for an example of how to insert and retrieve data from Azure. I have managed to insert data into the azure easy table (happy days).I want to know how to retrieve that data and display it in a list view or even an alertDialog builder for all i care just need a way to view the data in my app.
using the code below i have managed to enter some data into the azure database.
public void saveToAzure(){
button_save_to_azure = (Button)findViewById(R.id.btnSaveDataToAzure);
button_save_to_azure.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myAzuretbl.SEEDNAME = edittext_seed_name_for_azure.getText().toString();
mClient.getTable(Azuretbl.class).insert(myAzuretbl, new TableOperationCallback<Azuretbl>() {
#Override
public void onCompleted(Azuretbl entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
// Insert succeeded
Toast myToast = Toast.makeText(getApplicationContext(),"Inserted", Toast.LENGTH_LONG);
myToast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
myToast.show();
edittext_seed_name_for_azure.setText("");
} else {
// Insert failed
Toast myFailToast = Toast.makeText(getApplicationContext(),"Not Inserted", Toast.LENGTH_LONG);
myFailToast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
myFailToast.show();
edittext_seed_name_for_azure.setText("");
}
}
});
}
}
);
}
At the moment i can enter 1 field into the database and i know how to enter more. I would like to now retrieve this data.
my local azure table looks like this at the moment:
package com.jonnyg.gardenapp;
public class Azuretbl {
public String Id;
public String SEEDNAME;
}
nothing special but it does the job.
I have looked at the documentation and none of it makes sense to me.looking at the new quick start guide and then looking at the documentation are completely different.
from the way i am doing it here is there a follow up in retriving the data and viewing it in either a list view or alertDialog builder?.
#JonnyG,
Could you please try to use the excute() method and refer to SDK document (https://github.com/Azure/azure-mobile-services/blob/master/sdk/android/src/sdk/src/main/java/com/microsoft/windowsazure/mobileservices/table/MobileServiceTable.java )?
Generally, we can retrieve the table rows as following:
MobileServiceList<Azuretbl> result =mClient.getTable(Azuretbl.class).execute().get();
for(Azuretbl item:result)
{
//your code
}
Also, you can check this official document sample(https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-how-to-use-client-library/#querying)
Hope this helps.