Firebase get the reference of the child of a child - java

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) {
}
});

Related

Firebase onDatachange() to set value

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

Firebase database query to fetch particular data

My Database struckture
This is my database in Firebase and I'm developing an Android application. Now I want to retrieve all the data from "Generated" node where my current user's userid matches the "userId" in data.
I want to know the query in Firebase to fetch that particular data.
Firebase Query firebase query
Read the Firebase Realtime Database Documentation to get some idea firebase realtime database
To Get Current User Uid
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = user.getUid(); // user.getUid() will return null if you are not log in
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query query = db.child("Leads").child("Generated").orderByChild("userid").equalTo(current_uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do something
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or Try This One
db.child("Leads").child("Generated").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot ds: dataSnapshot.getChildren())
{
SomeClass someClass = ds.getValue(SomeClass.class);
if(someClass.getUid().equals("uid")){
// i don't if it is the best practice or not but you can do with this as well
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To access every item from that reference you will need something like this:
mDatabase.child("Leads").child("Generated").child(uid).addValueEventListener(new ValueEventListener() {
final List<String> lstItems= new ArrayList<String>();
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = (String) ds.getKey();
String values = (String) ds.getValue();
Log.e("Values",""+values );
lstItems.add(values );
}
PS: you can remove .child(uid) in your reference if you want to get all the children of Generated (it's going to be all the uids).

How to retrieve parent key of newly added child from Firebase using java

I want to retrieve "7753400075_Canada_twinpalms_||_twinpalms_20170824001545_F5BA7F33AD51CE283332001BEC409A46" key, How to do so? Here is my code...
ref.addValueEventListener(new ValueEventListener() { //addListenerForSingleValueEvent
#Override
public void onCancelled(DatabaseError arg0) {
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object response = dataSnapshot.getValue();
System.out.println("read data :"+response);
}
});
ref.child("chatmessage").child("devicetoken").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
// Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// System.out.println("previousChildName :"+previousChildName);
}
}
});
Here is the Firebase database example:
I tried using child data snapshot method but did not worked. It returns all data. But i need to get only the new child added parent. Any help for this will be much appreciated.
To solve this, you need to filter your results. Assuming that chatmessage is a direct child of your Firebase database root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference deviceTokenRef = rootRef.child("chatmessage").child("devicetoken");
Query query = deviceTokenRef.orderByKey().limitToLast(1);
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) {}
};
query.addListenerForSingleValueEvent(eventListener);

Firebase data retrieve with singlechildevent

Here is my firebase data structure . The child "Tags" is a child of root.
final Query searchquery = mDatabase.child("Tags").orderByKey().limitToFirst(10).startAt(s.toString().toLowerCase()).endAt(s.toString().toLowerCase() + "\uf8ff");
searchquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String u = dataSnapshot.child("article_name").getValue(String.class);
Toast.makeText(MainActivity.this,":/ : "+u.toString(),Toast.LENGTH_LONG).show();
}catch (Exception tg){
Toast.makeText(MainActivity.this,tg.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get the value of child "article_name" . I used the code above . But it is returning null .
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tagsRef = rootRef.child("Tags");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String article_name = ds.child("article_name").getValue(String.class);
Log.d("TAG", tagsRef);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
tagsRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Blood Circulation
Dummy Article
Also don't forget to use names for the keys that does not contain any spaces. So you need to change blood circulation in blood_circulation or bloodCirculation

Retrieve all data from Firebase Database

ANDROID: I have a Firebase database like this.
In my app, I would like to compile an arraylist that displays all values from the nameofEntry [DESCRIBED BELOW]. By this I mean the "balso," the "nairboh" and so on.
I have the references:
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference users = root.child("Users");
DatabaseReference childRef = users.child(userID);
DatabaseReference childRefNameNode = childRef.child(nameOfEntry);
childRefNameNode.child(nameOfEntry).setValue(nameOfEntry);
//FETCH DATA
childRefNameNode.child(nameOfEntry).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valueFromDB = dataSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But this only fetches for one entry. How can I get more entries? [All of them]?
You need to use this code snippet. You haven't used any for loop to step over your children.
EDIT: Also, update your database reference as:
//Updated ref
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);*
//add listener to updated ref
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the for loop here to step over each child and retrieve data
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
String valueFromDB = childSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Do let me know if it changes anything for you.

Categories

Resources