Firebase onDatachange() to set value - java

Is it possible to set the value using onDataChange() in Firebase? I do not know the value of the post key of each child.
Posts database
databaseReference2 = firebaseDatabase.getReference("Posts");
Query query2 = databaseReference2.orderByChild("userID").equalTo(currentUser.getUid());
query2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
for(DataSnapshot snap:snapshot.getChildren())
{
Post post = snap.getValue(Post.class);
post.setPicture(image);
post.setUserName(name);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});

Is it possible to set the value using onDataChange() in firebase?
Yes, it is.
I do not know the value of the post key of each child.
Actually, there is no need for that.
I just want to update the image and name of each post when users edited their profile name and image.
To achieve that, please use the following lines of code:
databaseReference2 = firebaseDatabase.getReference("Posts");
Query query2 = databaseReference2.orderByChild("userID").equalTo(currentUser.getUid());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Map<String, Object> update = new HashMap<>();
update.put("picture", image);
update.put("userName", name);
postSnapshot.getRef().updateChildren(update).addOnCompleteListener(/* ... */);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query2.addListenerForSingleValueEvent(valueEventListener);

You can use getkey() in ondatachange This will give you the keys you are talking to
for(DataSnapshot snap:snapshot.getChildren())
{
String keys = snap.getKey();
}

Related

How to get child key-value pairs in Firebase when immediate parent is known?

I have written the following code for searching the specific node and it does work correctly.
private void SearchFirebase() {
Rootref.orderByChild("IMG").equalTo(imUrl).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot product : snapshot.getChildren()){
id = product.getKey(); //returns the id(for eg. 8006)
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
But I don't know how to access the child key-value pairs once the specific parent key is known
In the picture above I need to fetch the key-value pairs such as Product Name or Product Discount etc.
You just have to add child to your reference and get data as explained in this answer
private void SearchFirebase() {
Rootref.orderByChild("IMG").equalTo(imUrl).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot product : snapshot.getChildren()){
id = product.getKey();
Log.i(TAG, Rootref.child(id).child("Product Discount").getValue(String.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
When querying a Firebase Realtime Database, the most convenient way for getting the data out is by calling the right child directly from "DataSnapshot" object and converting it to the right type, as explained in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
Query imgUrlQuery = productsRef.orderByChild("IMG").equalTo(imUrl);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String productDiscount = ds.child("Product Discount").getValue(String.class);
String productId = ds.child("Product Id").getValue(String.class);
String productName = ds.child("Product Name").getValue(String.class);
String productPrice = ds.child("Product Price").getValue(String.class);
String shopName = ds.child("Shop Name").getValue(String.class);
Log.d("TAG", productDiscount + "/" + productId + "/" + productName + "/" + productPrice + "/" + shopName);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
imgUrlQuery.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
0/8006/Frooti/50/shop-A

Retrieve and update child data in firebase

I have a problem with retrieving and updating a value from Firebase realtime database:
reff = FirebaseDatabase.getInstance().getReference("Items").child(a);
reff.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Items items = dataSnapshot.getValue(Items.class);
Integer na = items.getItemQuantity();
if (na <= 0) {
Toast.makeText(CheckOut.this, "Out of Stock", Toast.LENGTH_LONG).show();
} else {
na--;
snap.child("itemQuantity").getRef().setValue(na);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Error log on line 60 from the if-else.
According to your last comment:
yes a is the barcode that i will receive from barcode. itemQuantity of a single child.
To get the value of itemQuantity property of a single child, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference barcodeRef = rootRef.child("Items").child("1234567781");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long itemQuantity = dataSnapshot.child("itemQuantity").getValue(Long.class);
Log.d(TAG, String.valueOf(itemQuantity));
//Do what you need to do with itemQuantity
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
barcodeRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
14
The problem in your code is that you are looping through the dataSnapshot object using getChildren() method when is actually not necessary. You should only get the correct reference as in the above code and simply use the value of itemQuantity property as needed.

Retrieve specific value from Firebase database into string variable

I'm trying to retrieve a specific value from a Firebase realtime Database.
The data looks like this:
I want to get the URL value from any of them and then put it into a string variable to use later. This is so that the program does not need to be changed if the download link is changed. The code I have so far is;
DatabaseReference fdb = FirebaseDatabase.getInstance().getReference();
//Query query = fdb.child("URLDOWNLOADS").child("WSSeasons")
fdb.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot url : dataSnapshot.getChildren())
{
LoginInfoFirebasedb DownURL = url.getValue(LoginInfoFirebasedb.class);
String temp = DownURL.dwldURL;
URL1 = temp;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
Some help would be seriously appreciated. I understand this may be a simple problem but I am stumped.
To get each url as a String, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("URLDOWNLOADS");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
String url = ds.child("URL").getValue(String.class);
Log.d(TAG, key + " / " + url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);

Multiple Query and Ref Firebase Database Android

My firebase database looks like this:
From this query
String currentUserID = FirebaseAuth
.getInstace()
.getCurrentUser()
.getUid();
DatabaseReference favorsRef = FirebaseDatabase
.getInstance()
.getReference()
.child("favors");
Query myChatsQuery = favorsRef
.orderByChild("uid")
.equalTo(currentUserID);
I need to create other query to get just the tuples from myChatsQuery who has the child called "messages". If the tuple doesn't have the child "messages", I don't want to insert it in my new query.
So, How I can create a query from other query?
Help me please,
Thanks in advance.
Unfortunately, orderByChild() does not work on multiple same fields at once, so you may have to do the job in two steps.
First you can run an orderByChild() query looking for the currentUserId and then add all those that match to an ArrayList and then run orderByChild() in those found uids for messages.
This looks something like this, in code:
reference.orderByChild("uid").equalTo(currentUserId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
array.add(dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
)};
This code above adds uids matching currentUserId to the ArrayList array.
databaseReference.child(array.get(0)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("messages").exists())
// do your thing
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
)};
You can also just use a for loop to go through all the values in the array.
To solve this, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("favors").orderByChild("uid").equalTo(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
if(ds.child("messages").exists()) {
//Do what you need to do
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
As you can see, you can solve this by querying the database only once.

Firebase get the reference of the child of a child

As you see each post has a different Id (the user id who posted) I'm trying to get the reference of this child fx3RqooRMOVRaQHGas4OWQnFK593 for example so the database reference will be like this:
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Posts").child("fx3RqooRMOVRaQHGas4OWQnFK593");
But what I want is to get that reference dynamically for each post Id.
You have 2 option.
if u want to download one single post then u have to use your custom postId. you can't use pushId(). So that you will know which post u want to download and show.
how to make custom id
FirebaseDatabase.getInstance().getReference().child("Posts")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, Object> post = (HashMap<String, Object>) dataSnapshot.getValue();
total= post.size();
}
}
and then create custom id
FirebaseDatabase.getInstance().getReference().child("Posts").child("post"+total).setValue(YourValue);
option 2.
Simply download all post from the post node because u have to ..
FirebaseDatabase.getInstance().getReference().child("Posts")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
//here is your every post
String key = snapshot.getKey();
Object value = snapshot.getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Bonus
if u want to show post of a particular user. (I am assuming that)
u can store the push key inside the user object in a string arrylist. then just call them one by one ...
happy coding :) :)
To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(eventListener);
The output will be all those keys.
FirebaseDatabase.getInstance()
.getReference()
.child("Posts")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String key = snapshot.getKey(); // key here
Object value = snapshot.getValue(); // value here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources