I want to update the date on Firebase on a specific node.
DB Structure:
I am trying as
private void updateData() {
database = FirebaseDatabase.getInstance();
myref = database.getReference();
myref.child("myDb").child("awais#gmailcom").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("leftSpace").setValue(newValue);
dialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("User", databaseError.getMessage());
}
});
}
I want to update the leftSpace key with the value of newValue, newValue is the type of string here. But it is not updating the value in Firebase.
If I give here
dataSnapshot.getRef().child("leftSpace").setValue(765);
it updates well. But I want to update in the format of string on the Firebase.
I saved the data on Firebase of all string types. (My pattern class contains all of the type strings)
Why it is not updating the newvalue of type string here?
Edit 1 Suggested by #Rjz Satvara
You method is adding a new node under myDB as
It is not updating the already one.
In Firebase To update specific value you can use it...
ref.child("myDb").child("awais#gmailcom").child("leftSpace").setValue("YourDateHere");
or you can move into child using "/" as follow :
ref.child("myDb/awais#gmailcom/leftSpace").setValue("YourDateHere");
you can assign new value in same child,like
Firebase firebase = new Firebase("your database link/myDb");
firebase.child("awais#gmail.com").child("leftSpace").setValue("newValue");
According to Firebase Official Documentation you can update the specific node of parent node in this way
Using setValue() in this way overwrites data at the specified location, including any child nodes. However, you can still update a child without rewriting the entire object. If you want to allow users to update their profiles you could update the username as follows:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseRef = database.getReference();
mDatabaseRef.child("TABLE_NAME").child("orderStatus").setValue(2);
Note! TABLE_NAME mean your parent node whose child node you want to update.
Related
I'm having some trouble deleting nodes in Firebase
This is how I upload my data
BigBoy add = new BigBoy(addCate);
myRef.push().setValue(add);
This is how i'm trying to delete my data
databaseReference = FirebaseDatabase.getInstance().getReference().child("message");
myRef = database.getReference("message");
String sfasf = Utils.object.getSfasf();
DatabaseReference remove = FirebaseDatabase.getInstance().getReference("message").child(sfasf);
remove.removeValue();
But the problem is that the node is not being deleted.
Make your firebase call like this -
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("message");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
if (dataSnapshots.child("sfasf").exists()) {
dataSnapshots.child("sfasf").removeValue();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
1) You have a reference object but you dont use it. You have created 2 variable references and you dont use them.
2) Your code is wrong in order to remove the node you must specify the key
myRef = database.getReference("message");
myRef.child(key).remove();
---edit---
try this
myRef.child(key).removeValue();
---edit---
From the official documentation:
The simplest way to delete data is to call removeValue() on a reference to the location of that data. You can also delete by specifying null as the value for another write operation such as setValue() or updateChildren(). You can use this technique with updateChildren() to delete multiple children in a single API call.
The problem was that I wasn't referencing the pushID when I was referencing the specific data node. That was solved by saving the key as well when I upload the data.
DatabaseReference databaseReference=mDatabase;
String queryText="Hotel";
databaseReference.orderByChild("Coupon")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
Here I attached the code which I used to get child names of "Coupon" when I entered the "Hotel" query under the Coupon.But I got blank.I supposed to get Hotel1,Hotel2 object.I'm new to firebase.So hope your support .Thanks in advance.
In the Web version, they use something called ElasticSearch, you could try to read more here: https://firebase.googleblog.com/2014/01/queries-part-2-advanced-searches-with.html
But for Android, I think there isn't any functionality to perform a search like that. What I would do is to query all the records then filter them myself:
DatabaseReference databaseReference = mDatabase;
mDatabase.addValueEventListener(new ValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot val : dataSnapshot.getChildren()){
//I am not sure what record are you specifically looking for
//This is if you are getting the Key which is the record ID for your Coupon Object
if(val.getKey().contains("Hotel")){
//Do what you want with the record
}
//This is if your are querying for the hotel child
if(val.child("hotel").getValue(String.class).contains("Hotel")){
//Do what you want with the record
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
}
Don't load your whole database to filter out needed data. It produces unnecessary traffic which has to be loaded, calculated and deleted. Instead, use:
DatabaseReference myRef = FirebaseDatabase.getDatabaseReference();
Query searchQuery = myRef.child("Coupon").orderByChild("hotel").equalTo("yourSearchString");
To make this code work, you also have to add indexOn on your corresponding attribute in the rules (of Firebase Database console).
I have the following data structure on firebase for the user MF0qeRA4p7djfjgXxqwFOck3m6p02. I want to get the value of item3 to populate a single field into the User interface on an Android App. I have been looking through samples on Stackoverflow, but all I have found are outdated and do not work with the current version of firebase. I'm new to firebase completely and this is my first app on android. I've got the oncreate user method to populate the users email address and add the 4 item fields, but retrieving the data I'm completely lost and I am not sure where to even begin.
-Users
---MF0qeRA4p7djfjgXxqwFOck3m6p02
------item1:"1"
------item2:"2"
------item3:"3"
------item4:"4"
According to what I can identify is, you are facing problem retrieving data from this reference. Here is the code:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.child("MF0qeRA4p7djfjgXxqwFOck3m6p02").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map=(Map<String, Object>)dataSnapshot.getValue();
String item3=(String)map.get("item3");
display(item3);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.
You can create a custom model and inside you can insert elements. Something like this:
public class Item {
private List<Object> ojects;
}
There you can save instance of Item on database. In this case you have more controll. Other case is to use push() method, that will generate a new encoded key, something like this:
mDatabase.child("items").push().put(new Object());
I am trying to use the firebase push() function, as I want to add a list off data to an allready existing list. The setValue() function overwrites existing data.
This is what I used to do:
DatabaseReference childref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
childref.setValue(getAnsweredQuestions(questionViewList));
This worked, but every time I use this function the data is overwritten and this is not what I want. I tried using the Push function as described by the firebase documation: https://firebase.google.com/docs/database/android/save-data
I am not sure I am doing it right, but it is not working. And this is when I tried to implement the push() function:
DatabaseReference childref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
String key = childref.push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put( key, questionViewList);
mDatabase.updateChildren(childUpdates);
The exception I get is:
com.google.firebase.database.DatabaseException: Failed to parse node with class class scrambled.nl.generationr.QuestionView
And this is weird, since I did not receive this error while doing the setValue method. Can anyone explain what I am doing wrong and how I should push a list to firebase?
edit:
What I can do is:
DatabaseReference childref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
childref.push().setValue(getAnsweredQuestions(questionViewList));
In added the push() here. This works, but instead of just increasing my list, i add another layer in my list so I actually get an array of arrays instead of a longer list.
See here the result:
Saving a List of AnsweredQuestion objects:
This assumes you've followed the rules when designing your AnsweredQuestion.class so that the Java object can be used to store data in Firebase. If you need guidance for that check under the "Basic write operations" heading for saving data in the documentation.
//List of AnsweredQuestions
List<AnsweredQuestion> mAllAnswers;
....
//create the database reference that points to the correct parent node
//where answeres are stored for each user
DatabaseReference ref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
//Iterate over your List of AnsweredQuestion objects and use push() along with setValue()
//to store a single AnsweredQuestion object to a unique location in your database.
for(AnsweredQuestion answer : mAllAnswers){
ref.push().setValue(answer);
}
Retrieve all answered questions for a user:
//create List to store AnsweredQuestion object
List<AnsweredQuestion> mAllAnswers = new ArrayList<AnsweredQuestion>();
...
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//iterate over datasnapshot to get/store each AnsweredQuestion object
if(datSnapshot.exists()){
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
AnsweredQuestion answer = snapshot.getValue(AnsweredQuestion.class);
mAllAnswers.add(answer);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle error
}
});
There are multiple ways to retrieve the answers for each user, using .addListenerForSingleValueEvent() is just one way. You can also use a FirebaseListAdapter or FirebaseRecyclerAdapter if you wanted to display the answers in a ListView or RecyclerView.
I am using Firebase realtime database in Android app, and have data like this:
How can i delete the record "Apple" (marked in picture)?
According to the docs, to remove an item you call removeValue() on the reference. But to get the reference i require the child id. Because its a random generated id (-KISNx87aYigsH3ILp0D), how to delete it?
If you don't know the key of the items to remove, you will first need to query the database to determine those keys:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("firebase-test").orderByChild("title").equalTo("Apple");
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
appleSnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
this solved my problem
mPostReference = FirebaseDatabase.getInstance().getReference()
.child("quotes").child(mPostKey);
mPostReference.removeValue();
If you are using firebase-admin you can simply try this out as
admin.ref(`/users/${userid}`).remove()
and that works for me.
And also do remember to use async and await syntax.
You can use this code :
onDeletePost(id:string){
return this.http.delete(`https://my-angular8-prjt.firebaseio.com/posts/${id}.json`).subscribe();
}
Depending on how and why you are deleting the data you can use these:
// Could store the push key or get it after push
String newPostKey = yourDatabase.child('firebase-test').push({
something:something
}).key();
// Depends how you get to here
howYouGotHereId.parent().setValue(null);
Firebase Save Data 3.0
Assume that images is the directory of your firebase database which you want to clear.
private static DatabaseReference mDatabase;
public static void clearData(){
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("images").setValue(null);
}
Here images is the parent directory of the database. If you want to clear a nested directory (DCIM) inside the images directory so that you can retain the remaining data in it.
In that scenario you can do like this,
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("images").child("DCIM").setValue(null);
As a response to the query, Please try to use setValue method with null value setValue(null) to clear the data from firebase database
In the case of Firebase admin with python though:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
cred = credentials.Certificate("<your certificate>.json")
firebase_admin.initialize_app(cred, {'databaseURL': 'https://<your db>.firebaseio.com/'})
snapshot = db.reference('firebase-test').get()
for k,v in snapshot.items():
if v['title'] == "Apple":
db.reference('firebase-test').child(k).delete()