How to delete from firebase realtime database? - android

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()

Related

Having trouble deleting node in firebase database

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.

How to search for a values of Child in firebase Android

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).

Unable to retrieve data from Firebase database

I am making my first app using Firebase database. I was able to access the database before, but then I updated my SDKs and couldn't access the Firebase database. This is the function I use
notedatabase = FirebaseDatabase.getInstance();
DatabaseReference mrootDatabaseReference = notedatabase.getReference();
DatabaseReference firstchildref =mrootDatabaseReference.child(initpath);
When I run this it gives getserviceinstance failed error. When I try to debug the program the error states notedatabase= null. I have also changed the rules of my database. How do I fix this?
Sorry, this is my first time asking questions here, if I've left any information out kindly let me know. Thank you.
EDIT : The App works fine now I tried using
String initpath = intent.getExtras().getString("initpath","");
databaseref = FirebaseDatabase.getInstance().getReference();
final DatabaseReference numberofsubjectsRef = databaseref.child(initpath);
Try this one. More details on see an official link.
DatabaseReference databaseTracks;
List<Track> tracks;
databaseTracks = FirebaseDatabase.getInstance().getReference("tracks").child(intent.getStringExtra(MainActivity.ARTIST_ID));
#Override
protected void onStart() {
super.onStart();
databaseTracks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tracks.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Track track = postSnapshot.getValue(Track.class);
tracks.add(track);
}
TrackList trackListAdapter = new TrackList(ArtistActivity.this, tracks);
listViewTracks.setAdapter(trackListAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Okay as you are posting it for first time please make sure this things you have done correctly before making an firebase messaging app using realtime database.
1) you have created a project in firebase and added you project name and package correctly.
2)If in your firebase project rules(as above image) have been defined make sure to provide rules in place of Null it should be true, if you have not opted for any firebase authentication of firebase UI implementation.
3)your Initpath for child should be always same for accessing the same thread of message.

Updating the data on Firebase Android

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.

How to add new child in Firebase database Android

I'm trying to add a new child using the DatabaseReference in my Firebase Android app. I'm doing:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference()
mDatabase.child("childToAdd").setValue(1);
I can do this with a regular Firebase Reference as it would add the child to the database if it isn't there.
How could I go about doing this with DatabaseReference?
Edit: Thanks for all the suggestions but I'm having issues with the following code. When it enters the if block it does not push the data onto the database.
https://gist.github.com/rounaksalim95/a5cba332400c6caf8320f15b0cbf06e8
When I try this with the old Firebase reference I get error code 11 (User code called from firebase runloop) and with the new database reference I get error code -3 (PermissionDenied even though I have no security rules).
Update:
I got it to do what I wanted to using a single value event listener:
Firebase userRef = new Firebase(BASEURL + "userData");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user.getUid()).getValue() == null) {
userRef.child(user.getUid()).setValue(1);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
However database reference doesn't let me add values like this.
You'll need to call push() to generate a unique key for the new data:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference()
mDatabase.push().setValue(1);
This will append the new value at the end of the list.
By combining the push() and child() methods, you can create multiple lists of children in the database:
mDatabase.child("numbers").push().setValue(1);
mDatabase.child("numbers").push().setValue(53);
mDatabase.child("numbers").push().setValue(42);
mDatabase.child("letters").push().setValue("a");
mDatabase.child("letters").push().setValue("z");
mDatabase.child("letters").push().setValue("c");
See the section append to a list of data in the Firebase documentation.
Another post mentioned to check your gradle app file to ensure you have the latest version of the Firebase as follows:
compile 'com.google.firebase:firebase-core:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
I think this should fix many issues that could arise from using older versions.
I hope this helps.
You cannot add anything to the database if you're not authorized. You can do one of the following:
Either set this to your rules tab in firebase console:
{
"rules": {
".read": true,
".write": true
}
}
Or you must create an authentication first (try with email/pass) and create user with
createUserWithEmailAndPassword(email, password)
and then sign in with:
signInWithEmailAndPassword(email, password)
and you need to enable sign-in with email/pass in your console as well.
And then you can write data to your database.
Use push() before set value in the firebase. It will create new user every time when you send value in the database.
Check this sample, it may help you out.
public class FirebaseUserDetails
{
private String mDisplayName;
public String getmDisplayName() {
return mDisplayName;
}
public void setmDisplayName(String mDisplayName) {
this.mDisplayName = mDisplayName;
}
}
Add your value to firebase database,
FirebaseUserDetails firebaseUserDetails = new FirebaseUserDetails();
firebaseUserDetails.setmDisplayName("arunwin");
DatabaseReference pathReference = FirebaseDatabase.getInstance().getReference().child("contacts");
pathReference.child("arun").setValue(firebaseUserDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
And your result value will be added in your database like the below,
contacts:
arun:
mDisplayName:"arunwin"
In my case i am adding new child like this!
NOTE : Here i am adding new child refresh_token to my firebase database
FirebaseDatabase.getInstance().getReference().child("RegistrationModel").child(userId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> stringStringHashMap =(Map<String, String>) dataSnapshot.getValue();
stringStringHashMap.put("refresh_token",refreshedToken);
FirebaseDatabase.getInstance().getReference().child("RegistrationModel").child(userId)
.setValue(stringStringHashMap);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources