This question already has answers here:
How to remove child nodes in firebase android?
(4 answers)
Closed 5 years ago.
I use following code to add a child and set a value to it in FireBase.
String ref = Constants.Client+"/"+Constants.firebaseProjects+"/"+Constants.ProjectName+"/xyz";
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseRefer);
ref.child("mockChild").push().setValue("")
What can I do to delete the "mockChild" ?
ref.child("mockChild").removeValue();
Code to add child - ref.child("mockChild").push().setValue("Hello");
Code to remove child - ref.child("mockChild").removeValue();
Lets take an example in a user db:
ref.child("Users").child("User1").setvalue("User 1");
ref.child("Users").child("User2").setvalue("User 2");
ref.child("Users").child("User3").setvalue("User 3");
Now if you want to remove a specific user from the database you have to use this code:
ref.child("Users").child("User2").removeValue();
Since firebase is a key value database, it will remove the value from User2 and also the key since the key can't be on it's own. This will remove the entire reference to User2 from your database.
To solve this, please use the following code:
String key = ref.child("mockChild").push().getKey();
ref.child("mockChild").child(key).setValue("yourValue");
ref.child("mockChild").child(key).removeValue(); // This is how you remove it
or you can use:
ref.child("mockChild").child(key).setValue(null);
It's also accepted and means that when you give Firebase a null value for a property/path, you indicate that you want to property or path to be deleted.
If you want to remove the entire child, then just use:
ref.child("mockChild").removeValue();
Note, it will remove everything that mockChild contains.
Related
This question already has answers here:
How to add values to Firebase Firestore without overwriting?
(5 answers)
Why is my Cloud Firestore Transaction not merging when using SetOptions.merge()?
(1 answer)
Closed 4 years ago.
I'm new to Firestore and I am having some trouble even though I have gonne through the docs.
I have the following structure:
buses (collection) -> cb-123-1 (document) -> many custom objects
Now I am trying to add data following the docs:
PassengerModel passengerModel = new PassengerModel(
Integer.parseInt(seatNo.getText().toString()),
"selected");
mFirestore.collection("buses").document(mBusUid)
.set(passengerModel, SetOptions.merge());
Now the item is added alright on click however it replaces whatever exists in my document instead of adding to it.
I assume your PassengerModel class has all properties for the passenger. In that case the behavior is expected: Firestore loops through all properties of the class. If no value is present for a property, that property is deleted.
You're more likely looking to patch, which requires a data model that only has the properties that you want to modify. An easier and more common approach is to use a Map for patches, or this even simpler approach:
mFirestore.collection("buses").update(seatNo, Integer.parseInt(seatNo.getText().toString()))
I am working on an Android application where there are two types of user. I differentiate them into the system by using the field UserType. I have a requirement where I have to copy data from one child node into another. I am using Firebase for my backend. I have gone through other answers but this requirement is unique in a way that, I want to copy data only on a particular node. Attaching the Firebase database structure
In this structure, if you can see I have expanded 2 child nodes of "users". One of the child has userType as Standard User and other child has userType as Guardian User.
1) I want to copy the "fullNameGuardian" child alone from the user with key starting with "L4bTr6q" to the user with key starting with "dC9Mq"
2) I want to copy the "standardEmail" child alone from the user with key starting with "dC9Mq" to user with key starting with "L4bTr6q".
And everytime I add a new user, the user can be with one of the userType "Standard User" or "Guardian User". So is there a possibility like I do it for every new user?
I am having difficulties figuring out how to do this. Any help is appreciated. Thanks a lot in advance.
I think you could save the other structure when you save the first one. For instance,
Save - node1/child
Update - node2/child
//and so on
Another way is using Firebase functions(Real database triggers) in order to automatically do something after something else had happened. Check it out.
I have a realtive simple Firebase database, in which i have 2 models. A ListModel and a UserModel. In my Lists, i'm using push() method to generate unique ids. Each unique id i want to be added as a key and "true" as it's value under Users/gmail#gmail,com/Lists.
When i add the first list, the database looks like this:
And everything works fine, but when i try to add another one, the database looks like this:
In Users/gmail#gmail,com/Lists, the first one is overwritten by the second insert. How can i add the specific id and the specific value, as a new item as shown below?
And this is my code:
final UserModel um = new UserModel();
um.setUserEmail("gmail#gmail,com");
userDatabaseReference.setValue(um);
ListModel lm = new ListModel();
lm.setListName(listName);
listKeyDatabaseReference = listDatabaseReference.push();
listKey = listKeyDatabaseReference.getKey();
listKeyDatabaseReference.setValue(lm);
listDatabaseReference.child(listKey).child("Users").child("gmail#gmail,com").setValue("true");
userDatabaseReference.child("gmail#gmail,com").child("Lists").child(listKey).setValue("true");
Thanks in advance!
Check the official doc:
For basic write operations, you can use setValue() to save data to a specified reference, replacing any existing data at that path.
Your problem is here:
userDatabaseReference.setValue(um);
In this way you are overriding all children in the userDatabaseReference path.
It means that the first record in Users/gmail#gmail,com/Lists is just deleted when you are adding the second one.
Before using the
userDatabaseReference.setValue(um);
you can check if the record exists.
If doesn't exist use the setValue to add the user-model with all its data.
If it exists, just skip this step and add the data in the lists path inside the same user.
My code:
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NewQuestionData nqd = new NewQuestionData(question.getText().toString(),keywords.getText().toString(),description.getText().toString());
databaseReference.child(firebaseUser.getUid()).child("question"+Math.random()).setValue(nqd);
}
});
Every time I insert value into the database, it fails.
Problem is here:
child("question"+Math.random())
I want to add unique ID with every question.
Following works fine:
child("question")
Please share your valuable suggessions, How to insert unique child for every new question inserted into the Firebase Database.
Try this.
String key = databaseReference.child(firebaseUser.getUid()).child("question").push().getKey();
databaseReference.child(firebaseUser.getUid()).child("question").child(key).setValue(nqd);
// key is unique every time you add your new question.
For more info you can visit https://firebase.google.com/docs/database/android/read-and-write
OR
you can use System.currentTimeMillis()
It will give timestamp in long and is always unique.
databaseReference.child(firebaseUser.getUid()).child("question"+System.currentTimeMillis()).setValue(nqd);
The problem is that the random generator function Math.random() generates values between 0 and 1 which would have the decimal point - .
Now this decimal when added to a string would look something like question0.0001
If you check the Firebase documentation, you would see that . is a forbidden character in a key. So this would be your problem. If you at all want to generate a random value, use something which will generate random values from 0 to INTEGER_MAX.
To insert a child with a unique key without having to worry about it, call Firebase's push() method. See the Firebase documentation on appending data.
Your code could be:
databaseReference
.child(firebaseUser.getUid())
.push()
.setValue(nqd);
This will generate a unique key of the format specified in this blog post: The 2^120 Ways to Ensure Unique Identifiers.
If you still want to use the question prefix, you can use push() as a separate call (it's a client-side call that doesn't connect to the Database):
String key = databaseReference.push().getKey(); // gets a unique ID
databaseReference
.child(firebaseUser.getUid())
.child("question"+key)
.setValue(nqd);
I have some Edittext that allows the user to enter data:
AppName
Date
Title
Quantity
User
I started a new Firebase project and it is currently a blank slate.
I am setting up my Firebase instance like this:
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl("https://myapp.firebase.io");
How I want it is everytime a new adding occurs, I would like to add it like this (AppName is the common ground for all entry):
AppName
Date
Title
Quantity
User
Date
Title
Quantity
User
...
...
AppName
Date
Title
Quantity
User
Date
Title
Quantity
User
...
...
How can I do the following:
The first time it is added, the AppName will be the parent node, and
anytime after Firebase should check to see if the parent node exist
and is the same and add it to that, otherwise create a new parent node
and add the children node to the new parent node.
I currently have my auth set up like this:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
I had to change to true for my app to write to Firebase.
How can I:
Not register the user but only allow the app to able to write to
Firebase.
EDIT:
I am doing the following:
mDatabase.child("AppName").setValue(etName.getText().toString());
mDatabase.child("AppName").child("Date").setValue(etDate.getText().toString());
mDatabase.child("AppName").child("Title").setValue(etQuantity.getText().toString());
mDatabase.child("AppName").child("Quantity").setValue(User.getText().toString());
mDatabase.child("AppName").child("User").setValue(etUser.getText().toString());
Instead of adding, it is overwriting the previous entry. How can I append.
If I understood you, you need that not registered users could edit your database on Firebase and how to know If you added an ID.
First of all, as Ishan Fernando said, If you add data with the same id, this data will be overwrited, and using the push method, Firebase will create an unic ID to add you data
Read this: https://firebase.google.com/docs/database/android/read-and-write?hl=en
This Gist, thanks to the user realgt, could help you to know if the Appname exists or not: https://gist.github.com/anantn/4323949#gistcomment-998628
This will get all your data and you could check if you need add it or not
And, if you don't want to register users, but you need them to write the database, I think that you need to register them as anonymous users:
https://firebase.google.com/docs/auth/android/anonymous-auth
Firebase needs registered users (using social networks, email o anonymously) to modify it, so try the anonymous method. The problem is when the user get out of your app, this user will keep registered on your database. So, I recommend you, (Please, correct me if I'm wrong) to erase the user when onStop starts and create it again when onReady starts.
I hope it helps.