Reputation: 27
I have stored user posts details in Post node under USERID in firebase database accordingly in incremental order as Post1, Post2 so on. Now I want to retrieve all the data within Post node one by one in descending order as Post2, Post1 and show in custom listview. For retrieving single post node data it is working fine but not working for retrieving multiple/all post nodes.
Here is my firebase database image:
For showing all the posts i have tried this way:
dataref1.addValueEventListener(new
com.google.firebase.database.ValueEventListener() {
@Override
public void onDataChange(com.google.firebase.database.DataSnapshot
dataSnapshot) {
list.clear();
for(com.google.firebase.database.DataSnapshot dataSnap :
dataSnapshot.getChildren())
{
for(com.google.firebase.database.DataSnapshot datas :
dataSnap.getChildren()) {
DataModel datamodel =
dataSnap.getValue(DataModel.class);
list.add(datamodel);
}
}
CustomAdapter adapter = new CustomAdapter(Home.this,list);
listView.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
It is just showing the user name in custom listview.
I have checked many tutorials but haven't find the solution. Kindly help me out.
Thank you :)
Upvotes: 0
Views: 2239
Reputation: 138824
To display those posts you need to change a little bit your Firebase database. For the moment all your posts are nested under the uid
. You need to add another node, named posts
, a direct child of the uid
, in which you need to add all those post separately. Your database should look like this:
Firebase-root
|
---- city: "City Name"
|
---- email: "[email protected]"
|
---- //and so on
|
---- posts
|
---- post1
|
---- post2
|
---- post3
|
//and so on
To diplsy those posts, please use this code:
//get the uid
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
String uid = firebaseUser.getUid();
}
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child(uid).child("posts");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String description = ds.child("description").getValue(String.class);
String dateTime = ds.child("dateTime").getValue(String.class);
String posturi = ds.child("posturi").getValue(String.class);
String severity = ds.child("severity").getValue(String.class);
Log.d("TAG", description + " / " + dateTime + " / " + posturi + " / " + severity);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
Upvotes: 1
Reputation: 494
FirebaseUI library make it very easy. Allow you to use FirebaseRecyclerAdapter to populate a RecyclerView
Here the official guide
Upvotes: 0