How to retrieve data from 2 tabels in firebase db android? - android

Here is my db format:
{
"classes": {
"class1": {
"name":"C1"
},
"class2": {
"name":"C2"
}
},
"students": {
"student1": {
"name":"S1"
},
"student2": {
"name":"S2"
}
},
"classes_enrollments": {
"class1": {
"student1": true,
"student2": true
},
"class2": {
"student1": true
}
},
"students_enrollments": {
"student1": {
"class1": true,
"class2": true
},
"student2": {
"class1": true
}
}
}
I want to get data like : class1 named C1, has 2 students S1 and S2
I tried this way
database.child("classes_enrolments").addValueEventListener(eventListener);
but the output is just the data of classes_enrolments node: {class2={student1=true}, class1={student2=true, student1=true}}
How to achieve it, please?
Thank you

To solve this, please use the cpde below:
String class1 = "class1";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("classes").child(class1).child("name");
ValueEventListener nameValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot nameDataSnapshot) {
String className = nameDataSnapshot.getValue(String.class);
Log.d(TAG, class1 + " named " + className);
DatabaseReference class1Ref = rootRef.child("classes_enrollments").child(class1);
ValueEventListener class1EventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long numberOfStudent = dataSnapshot.getChildrenCount();
Log.d(TAG, "has " + numberOfStudent + " students");
for(DataSnapshot studentDataSnapshot : dataSnapshot.getChildren()) {
String student = studentDataSnapshot.getKey();
DatabaseReference studentsRef = rootRef.child("students");
DatabaseReference studentRef = studentsRef.child(student);
ValueEventListener studentsValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d(TAG, name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
studentRef.addListenerForSingleValueEvent(studentsValueEventListener);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
class1Ref.addListenerForSingleValueEvent(class1EventListener);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
nameRef.addListenerForSingleValueEvent(nameValueEventListener);
In order to solve this, you should first get the name of the class, the query to get the number of student and in the end to get the name of the students. The result in the logcat will be:
class1 named C1
has 2 students
S1
S2

Related

How to retrieve data from specific node from firebase in android

I am trying to retrieve phonenumbers joined under CircleMembers of current user but datasnapshot returning null.Please help me out.Which is proper way to retrieve members under mycircle.
My firebase database is below
Here is my code.
userReference = FirebaseDatabase.getInstance().getReference().child( "Users" );
databaseReference = FirebaseDatabase.getInstance().getReference().child( "Users").child( user.getUid() ).child( "CircleMembers" );
databaseReference.addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
nameList.clear();
if(dataSnapshot.exists()){
for(DataSnapshot dss:dataSnapshot.getChildren()){
String circlememberID = dss.child( "CircleMembers" ).getValue(String.class);
userReference.child( circlememberID )
.addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
phone = dataSnapshot.getValue( Phone.class );
//fetching phone numbers under Circlemembers (to which circle current user is joined)
nameList.add( phone);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText( getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT ).show();
}
} );
adapter = new MembersAdaptor(nameList,getApplicationContext());
recyclerView.setAdapter( adapter );
adapter.notifyDataSetChanged();
}
}
else{
Toast.makeText( getApplicationContext(), "No circle", Toast.LENGTH_SHORT ).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
} );
To get all those phone numbers that exist under the CircleMemebers node, please use the following code:
String phoneNo = FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference circleMemebersRef = rootRef.child("Users").child(phoneNo).child("CircleMemebers");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String phoneNumber = ds.getValue(String.class);
Log.d(TAG, phoneNumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
circleMemebersRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
+919212143422
+615325453454
Give this a trial. I think this is the way your code should go:
userReference = FirebaseDatabase.getInstance().getReference().child( "Users");
//Changed databaseReference to userCircleMembersRef for easier understanding of nodes
userCircleMembersRef =
userReference .child( user.getPhoneNumber()).child( "CircleMembers" );
userCircleMembersRef.addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
nameList.clear();
if(dataSnapshot.exists()){
for(DataSnapshot dss:dataSnapshot.getChildren()){
Phone phone = dss.child( user.getUid()).getValue( Phone.class );
//fetching phone numbers under Circlemembers (to which circle current user is joined)
nameList.add( phone);
}
adapter = new MembersAdaptor(nameList,getApplicationContext());
recyclerView.setAdapter( adapter );
adapter.notifyDataSetChanged();
}else{
Toast.makeText( getApplicationContext(), "No circle", Toast.LENGTH_SHORT ).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText( getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

Android Firebase Database - Retrieving data

I am developing an Android app that uses Firebase database.
"posts": [
{
"post_id": 100,
"post_kind": "V"
},
{
"post_id": 100,
"post_kind": "S"
},
{
"post_id": 100,
"post_kind": "S"
}
]
I want query select all post where post_kind = S
I'm using query
databaseReference = firebaseDatabase.getReference("posts");
query = databaseReference.orderByChild("post_kind").equalTo("S");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
List<Post> list = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = (Post) snapshot.getValue(Post.class);
list.add(post);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DatabaseError", databaseError.toString());
}
});
But not result
Try this.
databaseReference = firebaseDatabase.getReference("posts");
query = databaseReference.orderByChild("post_kind").equalTo("S");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
int postId = snapshot.child("post_id").getValue();
String postKind = snapshot.child("post_kind").getValue();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DatabaseError", databaseError.toString());
}
});
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("posts").orderByChild("post_kind").equalTo("S");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Post post = ds.getValue(Post.class);
list.add(post);
}
Log.d("TAG", list.toString);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DatabaseError", databaseError.toString());
}
};
query.addListenerForSingleValueEvent(eventListener);

Firebase Query get values

I have a list of Child-Data and wants to have a certain value.
My Firebase structure:
Now, I only have the Child "Text" and the currendUser "0zwtyRwgnogC8Qk91AtHj7amZb63"
So how can I get the values of "text and "user_id"?
My source code:
mDatabaseText = FirebaseDatabase.getInstance().getReference().child("Text");
query = mDatabaseText.startAt(mCurrentUser.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot textSnapshot : dataSnapshot.getChildren()) {
/* String text = textSnapshot.getKey();
Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show(); */
TextModel textModel = chatSnapshot.getValue(TextModel.class);
String t = textModel.getText();
Log.i("!!!!!!!text", t);
Toast.makeText(getActivity(), t, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But this code doesn't work, why?
I used the query startAt.
Please use this code:
FirebaseDatabase rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference currentUserIdRef = rootRef.child("Text").child(currentUserId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = (String) ds.getKey();
DatabaseReference userIdRef = rootRef.child("Text").child(currentUserId).child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user_id = (String) dataSnapshot.child("user_id").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
};
currentUserIdRef.addListenerForSingleValueEvent(eventListener);
In which currentUserId is the variable that you say you already have it.
Hope it helps.

get Firebase nodes by children

If I have a database that is set up like so
-users
-uId0
-Name: "Bill"
-uId1
-Name: "Bob"
-uId2
-Name: "Dave"
How do I get the uId elements if there name child starts with B.
The query should return somthing like this?
-uId0
-Name: "Bill"
-uId1
-Name: "Bob"
Thanks!!
DatabaseReference myReference = FirebaseDatabase.getInstance().getReference();
myReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//looping all your users
for (DataSnapshot messageSnapshot:dataSnapshot.getChildren())
{
name = (String)messageSnapshot.child("Name").getValue();
if (name.toLowerCase().contains("b")) {
//u can save your name with 'b' string here
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To achieve this, please use this code:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users");
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String uId = (String) ds.getKey();
DatabaseReference uIdRef = FirebaseDatabase.getInstance().getReference().child("users").child(uId);
uIdRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("Name").getValue();
if (name.matches("^[B].*$")) {
System.out.println(name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});

Android RecycleView does not show data in list

this.books = new ArrayList<>();
mFirebaseDatabaseReference.child(SellBooksPost).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot AdataSnapshot) {
for (final DataSnapshot AmessageSnapshot : AdataSnapshot.getChildren()) {
bFirebaseDatabaseReference.child(mUserId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot BdataSnapshot) {
for (DataSnapshot BmessageSnapshot : BdataSnapshot.getChildren()) {
if (BmessageSnapshot.child("book").getValue().toString().equals(AmessageSnapshot.child("SellBooksPostId").getValue().toString())){
Log.d("INFO", "SELL BOOK book " + BmessageSnapshot.child("book").getValue());
Log.d("INFO", "SELL BOOK DETAIL " + AmessageSnapshot.child("SellBooksPostId").getValue());
books.add(new Book(
AmessageSnapshot.child("SellBooksPostId").getValue().toString(),
AmessageSnapshot.child("bookTitle").getValue().toString()
));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
saleBookPostAdapter = new SaleBookPostAdapter(getApplicationContext(), books);
mRoomRecyclerView.setHasFixedSize(true);
mRoomRecyclerView.setAdapter(saleBookPostAdapter);
It's hard to say if this is a problem, but I do not see a call to RecyclerView.Adapter#notifyDataSetChanged() method after updating the data. So try call
salesBookAdapter.notifyDataSetChanged()
after
books.add(new Book(
AmessageSnapshot.child("SellBooksPostId").getValue().toString(),
AmessageSnapshot.child("bookTitle").getValue().toString()
));

Categories

Resources