how to get all child nodes from firebase database? - java

this is my structure. i am trying to code a scoreboard for my app but i cant get the username & score. i want to safe that username & score in a sorted list to get the top 10.
this is my code: i onle get the usernames.
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Userlist = new ArrayList<String>();
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
for (DataSnapshot as : dataSnapshot.getChildren()) {
String userkey= as.getKey();
Userlist.add(userkey); //add result into array list
}
}
un.setText(Userlist.get(2));
}
#Override
public void onCancelled(DatabaseError error) {
}
});

Try the following:
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Userlist = new ArrayList<String>();
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
String userkey = dsp.getKey();
String scores = dsp.child("scorehigh").getValue().toString();
Userlist.add(userkey); //add result into array list
}
}
un.setText(Userlist.get(2));
}
#Override
public void onCancelled(DatabaseError error) {
}
});
The reference is at Users then you need to loop twice to be able to access the attributes scorehigh and username

Related

Get values only from second request

I have a problem i get value from Firebase, but the email only fills up after activity run second time.
private ArrayList<String> currentList = new ArrayList<>();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("userTable").child(user.getUid()).child("Container");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
First time size = 0;
Second time = 3(true result);
update UI after getting response.hope now it will work fine for you
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase listener is async, which means it will run in the background and not stop the code until you recieve a response.
In your code you don't wait for the value to be returned from the server, that why size=0.
what you need to do is check the size inside the listener and after the for loop :
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
This way you will wait for the value to be returned from firebase and then get the list size.

Getting Data from Firebase realtime database, Android Studio, Java

I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
name[] is an array of strings!

Retrieving all the passenger id (user id) inside the driver's passengerRequest node in Firebase and Android Studio

I'm trying to retrieve and convert it to strings the UserIDs that are being saved within the driver's passengerRequest like in this picture:
https://imgur.com/a/F6matnZ
here is my getAssignPassenger
private void getAssignedPassenger() {
String driverID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
passengerID = dataSnapshot.getValue().toString();
getAssignPassengerPickUpLocation();
}else{
passengerID = "";
if(pickupMarker !=null){
pickupMarker.remove();
}
if(AssignPassengerPickupLocationListener!= null){
AssignPassengerPickupLocationref.removeEventListener(AssignPassengerPickupLocationListener);
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
my problem is here in this block
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
passengerID = dataSnapshot.getValue().toString();
getAssignPassengerPickUpLocation();
in the passengerID it should retrieve every userIDs that are saved in there...
how do I that?
Next problem is... IF I successfully retrieved the userIDs and how do I continue it in finding their location, here is picture of the node:
https://imgur.com/1TQQ4Ih
I already started the codes for it
here is my getAssignPassengerLocation
private void getAssignPassengerPickUpLocation() {
AssignPassengerPickupLocationref = FirebaseDatabase.getInstance().getReference().child("passengerRequest").child(passengerID).child("l");
AssignPassengerPickupLocationListener = AssignPassengerPickupLocationref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()&&!passengerID.equals("")) {
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLong = 0;
if (map.get(0) != null) {
locationLat = Double.parseDouble(map.get(0).toString());
}
if (map.get(1) != null) {
locationLong = Double.parseDouble(map.get(1).toString());
}
LatLng driverLatLng = new LatLng(locationLat, locationLong);
mMap.addMarker(new MarkerOptions().position(driverLatLng).title("Pickup Location").icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher_pickup_marker)));
what should I do in this block
AssignPassengerPickupLocationref = FirebaseDatabase.getInstance().getReference().child("passengerRequest").child(passengerID).child("l");
AssignPassengerPickupLocationListener = AssignPassengerPickupLocationref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()&&!passengerID.equals("")) {
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLong = 0;
is it possible to store the nodes in an Array String?
For the first one
You have to get snapshot children inside snapshot
private void getAssignedPassenger() {
String driverID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
List<String> passengerIdList = new ArrayList()
for (DataSnapshot passenger Snapshot: dataSnapshot.getChildren()) {
String passengerId = passenger.getKey()
passengerIdList.add(passengerId)
}
getAssignPassengerPickUpLocation();
}else{
passengerID = "";
if(pickupMarker !=null){
pickupMarker.remove();
}
if(AssignPassengerPickupLocationListener!= null){
AssignPassengerPickupLocationref.removeEventListener(AssignPassengerPickupLocationListener);
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
For the second one
Actually you have to keep location same position as 'destination' instead of query in another children.
But why you need to get all users request location at the same time or inside your activity contain all users request location in one activity?
For more information:
Read and write lists
https://firebase.google.com/docs/database/android/lists-of-data
and
How to structured NoSQL
https://www.youtube.com/watch?v=v_hR4K4auoQ

Firebase Data retrieval in array

This is my Firebase realtime database structure:
How to get these data in a List to pass the data to the Model Class.
When I tried by generation data like below and it works.
listCourse = new ArrayList<>();
listCourse.add(new CourseModel("UserID", "CourseCode", "CourseName"));
listCourse.add(new CourseModel("122345", "TMN1234","System Programming"));
I just want get the data from firebase in this format..
You can retrieve list by this method.
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.i("Count " ,""+snapshot.getChildrenCount());
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
CourseModel course = postSnapshot.getValue(CourseModel.class);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
});
Please refer this documentation: https://firebase.google.com/docs/database/android/lists-of-data
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
I figured it out.. this is working for me..
To Access Child you can to create reference.!
DatabaseReference userRef= FirebaseDatabase.getInstance().getReference("users");
DatabaseReference userChildRef= userRef.child(childId);
DatabaseReference userCourseRef= userChildRef.child("courses");
DatabaseReference userCourseIdRef= userCourseRef.child(courseId);
userCourseIdRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
Tol solve this, there are to ways. First would be to get the data as objects of CourseModel class like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference coursesRef = rootRef.child("Users").child(uid).child("Courses");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<CourseModel> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
CourseModel courseModel = ds.getValue(CourseModel.class);
list.add(courseModel);
}
//Do what you need to do with the list of CourseModel objects
Log.d("TAG", list.ToString);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
coursesRef.addListenerForSingleValueEvent(valueEventListener);
The second one, would be to get the courseName as a String like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference coursesRef = rootRef.child("Users").child(uid).child("Courses");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String courseName = ds.child("CourseName").getValue(String.class);
list.add(courseName);
}
//Do what you need to do with the list of strings
Log.d("TAG", list.ToString);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
coursesRef.addListenerForSingleValueEvent(valueEventListener);

How to get list of root firebase database

I'm trying to get a list of one of my root nodes of my database
my database is set up like this
beans-card
--user
--008675
--...
--...
--...
--007865
--...
--...
--...
and so on...
i'm trying to get a list of the user which is made up of 6 digit string.
my code to read is
DatabaseReference list_db = FirebaseDatabase.getInstance().getReference();
list_db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getAllTask(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void getAllTask (DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
Users users = singleSnapshot.getValue(Users.class);
allUsers.add(users);
}
recyclerViewAdapter = new RecyclerViewAdapter(this,
allUsers);
recyclerView.setAdapter(recyclerViewAdapter);
}
and the error im currently getting is
11-28 13:44:38.622 23572-23572/ca.mobile.jenovaprojects.rewardsreader W/ClassMapper: No setter/field for 778018 found on class ca.mobile.jenovaprojects.rewardsreader.main.models.Users
for each user thats in the database.
thanks for any insight
To get those user 6 digit ids into a list, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.getKey();
list.add(userId);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
Now the list contains: 008675, 007865 and so on.

Categories