Having trouble deleting node in firebase database - android

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.

Related

Firebase and recyclerView

Hi I'm new in firebase and android studio and I have a problem
I want to store the data of this database in an array and next use the array to make a recycler view
Then in the main activity I wrote this:
And if I run the app only this is shown:
But if I do the same but instead of firebase i use a String[] with the data i want to show it works but i don't know why with firebase i can't.
if I change the references by this:
reference = database.getReference(FirebaseReferences.POKEMONS_REFERENCES);
reference.child(FirebaseReferences.APP_REFERENCES).addValueEventListener(new ValueEventListener() {
when I run the app, it automatically closes and i don't know what to do.
Could you please tell me what i'm doing wrong?
Thank you in advance.
Here is the logCat
https://github.com/adcasna/SearchViewPrueba2/wiki
Fisrts of all, please note that the Firebase documentation recommends against using arrays. Using an array is an anti-pattern when it comes to Firebase. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write. If you still want to use this kind of structure, for getting those names and store them in an ArrayList, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference appRef = rootRef.child("pokemons").child("app");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String c_name = ds.child("c_name").getValue(String.class);
list.add(c_name);
Log.d("TAG", c_name);
}
Log.d("TAG", list );
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
appRef.addListenerForSingleValueEvent(eventListener);

I can't get the key of firebase database

In my solution I save data from Windows form application. There is no problem. I can list them in my android app. On this point I am trying to get key value to update the data, but always I get null.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myReference = database.getReference();
Query myTopPostsQuery = myReference.child("DURUSLAR").orderByChild("kayitid").equalTo("1298843637");
myTopPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
//Childadi =postSnapshot.getKey().toString();
String anahtar=postSnapshot.getKey().toString();
Toast.makeText(getApplicationContext(),anahtar,Toast.LENGTH_LONG);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can you please help me?
When you execute a query at a location in the Firebase Database, it will search for the property you order/filter on in each child under that location. Since you query in /DURUSLAR, Firebase looks for /DURUSLAR/{something}/kayitid. Such a property does not exist, since you only have /DURUSLAR/{something}/{pushid}/kayitid.
To fix this problem you have two options:
query at a lower level
query to the property at its (fixed) path
The first option is to create the query at a lower level in the tree:
Query myTopPostsQuery = myReference.child("DURUSLAR/K6").orderByChild("kayitid").equalTo("1298843637");
Now the query is looking for /DURUSLAR/{pushid}/kayitid and it will work.
The second option is to query for the known path of the property:
Query myTopPostsQuery = myReference.child("DURUSLAR").orderByChild("K6/-KknsAR4_KFAeZ1HVXPW/kayitid").equalTo("1298843637");
It seems unlikely you want this here, but the approach may be helpful in other situations. Often when you need this approach with push IDs in the path, you'll want to look at http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value.
The reason you are getting null is because you are doing orderByChild on the wrong level of data . According to your data u need to have a child K4-> which has a unique_id_push_id -> kayitid.Therefore you need to traverse the K4 in order to get 1298843637 for key kayitid.You can follow this tutorial to understand the retrieving of data from firebase .
Query myTopPostsQuery = myReference.child("DURUSLAR").child("k6").orderByChild("kayitid").equalTo("1298843637");
myTopPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
//Childadi =postSnapshot.getKey().toString();
String anahtar=postSnapshot.getKey().toString();
Toast.makeText(getApplicationContext(),anahtar,Toast.LENGTH_LONG);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

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

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 delete from firebase realtime database?

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

Categories

Resources