I have a firebase data structure for my android app and I want to retrieve the data from random keys generated by push() method which is child of Forum node which is a child of root of the database. Please suggest me a way to do this. Thanks.
To display the values of all the children under Forums node, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference forumsRef = db.child("Forums");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String ques = ds.child("ques").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String uid = ds.child("uid").getValue(String.class);
Log.d("TAG", name + " / " + ques + " / " + title + " / " + uid);
}
}
#Override
public void onCancelled(DatabaseError error) {
Log.d("TAG", error.getMessage()); //Never ignore potential errors!
}
};
forumsRef.addListenerForSingleValueEvent(valueEventListener);
You can get all of the children nodes of the parent "Forum" node. Just use getChildren() method. Then just randomly select one of the child node at position index.
DataSnapshot snapshot = dataSnapshot.child("Forums");
Iterable<DataSnapshot> children = snapshot.getChildren();
for (DataSnapshot child: children) {
Object obj = child.getValue(Object.class);
}
first you should write your class model "FormusModel" to store the data from server
you can use this
> >
rootRef.child("Forums").addChildEventListener(new
> ChildEventListener() {
> > #Override
> > public void onChildAdded(DataSnapshot dataSnapshot, String s) {
> > ForumsModel model = dataSnapshot.getValue(FormusModel.class);
//now you can use model.getname();....
> }
Note: you must implemnt another method like onChildCahnge listener
Related
I am trying to retrieve data from Firebase, but I don't know how. I have the following data structure in Firebase [1]: https://i.stack.imgur.com/vN7Ge.png:
![enter image description here][1]
I can retrieve the category title(sleep, Stress Relief, and Relax), but don't know how to retrieve the author.
dataSnapshot.child("author").getValue(String.class)) ; doesn't work.
.
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
}
public void getDataFromFirebase() {
List<ParentItem> parentItemsList = new ArrayList<>();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
String category = dataSnapshot.child("Category").getValue(String.class));
String author = dataSnapshot.child("author").getValue(String.class));
}
Log.d("TAG", "onDataChange: "+ parentItemsList);
}
UPDATE
now I have the following code to retrieve data, but onDataChange () is never reached.
list.add("Milena"); // this word shows in recyclerview
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list.add("M");
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String category = ds.child("Category").getValue(String.class);
list.add(category);
for (DataSnapshot data : dataSnapshot.getChildren()) {
author = data.child("author").getValue(String.class);
list.add(author);
}
}
}
firebase rules:
{
"rules": {
".read": "auth==true",
".write": "auth==true"
}
}
I have line list.add("Milena") to make sure the problem is with firebase, not the recycler view itself. Recycler view shows only the word "Milena". And I have line as the first line of OnDataChange method list.add("M"). The recycler view doesn't shows the letter.
I already added google-services.json file to my app and added this line to manifest <uses-permission android:name="android.permission.INTERNET"/>
Why I can't still retrieve data?
If you want get field author, you can more loop for dataSnapshot like this
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
String category = dataSnapshot.child("Category").getValue(String.class));
for(DataSnapshot data : dataSnapshot.getChildren()) {
String author = data.child("author").getValue(String.class));
}
}
hope this can solve your problem :)
I think that the problem is your reference points to Category and you want the author. Between category and authors there are 2 children ("Sleep" and "1").
So, I think the best to do is change this line:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
in this:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category").child("Sleep").child("1");
To solve this issue you have to iterate through the children twice, as seen in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference categoryRef = db.child("Category");
categoryRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot categorySnapshot : snapshot.getChildren()) {
String categoryName = categorySnapshot.getKey();
Log.d("TAG", categoryName);
for (DataSnapshot ds : categorySnapshot.getChildren()) {
String author = ds.child("author").getValue(String.class);
Log.d("TAG", author);
}
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
But be aware that a child as Category: "Sleep" should not exist on the same level as 1, 2, and so on. Since the name of the category already exists as the key of a node, please remove those records:
In this way, you'll avoid a ClassCastException, as at the same level you have an object with two properties and a String one. So once you remove those children, the above code will work perfectly fine. If you however need a node to contain that information, I recommend you create a top-level node that will contain only the name of the categories.
I am working with firebase database and i was trying to get the value of a child using this code below and may System.out.println(MyCredit.toString()); is always returns null: Please see my firebase database
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
CollectCredits((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
private void CollectCredits(Map<String,Object> users) {
MyCredit = new ArrayList<>();
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){
//Get user map
Map singleUser = (Map) entry.getValue();
//Get Credit field and append to list
MyCredit.add((Long) singleUser.get("Credit"));
Toast.makeText(MainActivityCustonlistViewnew.this, "Credit : " +String.valueOf(MyCredit), Toast.LENGTH_SHORT).show();
}
System.out.println(MyCredit.toString());
}
Try this:
private void CollectCredits(DataSnapshot dataSnapshot) {
MyCredit = new ArrayList<>();
//iterate through each dataSnapshot
for (DataSnapshot d1 : dataSnapshot.getChildren()){
MyCredit.add(d1.getValue());
}
}
Let me give you some suggestions, Try to check your firebase database path both the root and child path because some time you did everything correctly but the path you specified to your Database reference which is not referring to the correct path. So it can produce the same result what are getting right now.
In my Firebase Database I have data laid out as such:
paidRecord[
John Smith: UNPAID
Bill Smith: PAID
Mary Smith: UNPAID
]
I am trying to create a String in my app that will display the paid status of all the people. At the moment all I have is a String that displays "UNPAID PAID UNPAID" but what I need is to display the users names as well.
Here is the function:
private void checkPaidStatus(){
paidString = "";
FirebaseDatabase.getInstance().getReference("Flats").child(flatID).child("Bills").child(itemSelected).child("paidRecord").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null){
Iterator<DataSnapshot> iterable = dataSnapshot.getChildren().iterator();
//this is the bit that needs to be changed to return properly xd good luck
for (Iterator<DataSnapshot> it = iterable; it.hasNext();){
DataSnapshot dataSnapshot1 = it.next();
paidString = paidString + "new" + dataSnapshot1.getValue(String.class);
textViewPaidStatus.setText(paidString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
So, is there a way on Firebase Database to return not only the value assigned to a key, but the key itself as well?
Actually, your key is also available in your sub-DataSnapshot just you need to get like bellow
DataSnapshot dataSnapshot1 = it.next();
paidString = paidString + "new" + dataSnapshot1.getValue(String.class);
textViewPaidStatus.setText(paidString);
String mStrkey=dataSnapshot1.getKey()
I am developing a team chat application . I am storing chat data in firebase.
This is my Data structure
The chats are stored under a node named chats.
each immediate child of chats is the name of a team(like whatsapp.. chat groups).
the team node have all chat messages. the chat messages are stored
with a parent node in the format timestamp_chat
My Problem
Now I have to create a firebase query to fetch this team nodes by from key.
That is
if a from: field contains the a given search value (say, "ragesh"), then the parent node "team_name" have to be returned(say,"teamrova") as a datasnapshot.
Simply speaking , I want datasnapshot of teams that have a particular username in the from field.
My Work
I tried the follwing code :
reference1 = FirebaseDatabase.getInstance().getReference().child("chats");
Query chatQuery = reference1.orderByChild("from").equalTo("ragesh");
System.out.println("Chat list :: starting");
chatQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("Chat list :: onChildAdded");
for (DataSnapshot chat : dataSnapshot.getChildren()) {
HashMap<String, Object> hashMap = (HashMap<String, Object>) dataSnapshot.getValue();
System.out.println("Chat list :: The chat group is =>" + dataSnapshot.getKey());
System.out.println("Chat list :: The key & Value => " + chat.getKey() +" :: "+chat.getValue().toString());
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ChatListActivity.this, "Connection Error "+databaseError.getDetails(), Toast.LENGTH_SHORT).show();
System.out.println("Chat list :: databaseError "+databaseError.toString());
}
});
Sadly , above code don't return any value. even the
System.out.println("Chat list :: onChildAdded"); not called. And it
doesn't calls onCancelled also.(so,no error).
I get sturcked by this. please help me.
To get the username:
mRootRef.child("chats").child("teamrova").orderByChild("from").equalTo("ragesh").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String name=datas.child("from").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Since you are using addChildeventListener then you do not need the for loop to be able to get those values for (DataSnapshot chat : dataSnapshot.getChildren()) {
You also need to change this:
reference1 = FirebaseDatabase.getInstance().getReference().child("chats");
to this:
reference1 = FirebaseDatabase.getInstance().getReference().child("chats").child("teamrova");
The above code is an alternative with addValueEventListener
Now what I am trying to do is to get all the children having category value of shop
I have tried this code
Firebase ref = new Firebase("https://top-africa.firebaseio.com/businesses/);
ref.orderByChild("category").equalTo("shop");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object ob = dataSnapshot.getValue();
System.out.println("There are " + dataSnapshot.getKey() + " blog posts==" + dataSnapshot.getValue());
}
});
but when I look at the log it printed out all 10 children whereas I suppose I would retrieve only one because there was only one value for category shop.
I don't know what I am missing. Could you please help me to solve the issue?
your reference is pointing to bussiness, so use query to fetch the data with condition
Query mQuery = ref.orderByChild("category").equalTo("Shop");
mQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object ob = dataSnapshot.getValue();
System.out.println("There are " + dataSnapshot.getKey() + " blog posts==" + dataSnapshot.getValue());
}
});