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.
Related
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!
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
So I have some data in my Firebase. It's structure is
(assume that there is more data)
I want to get the records where banknoteType ="100_dollar" and userId="1057..."
DatabaseReference database = FirebaseDatabase.getInstance().getReference("userBanknoteAmount");
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//todo
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
But the onDataChangeevent doesn't fire... What am I mistaking?
EDIT: I am trying to debug it and neither onDataChange nor onCancelled breakpoints stop there
EDIT 2 : The current code I am using is
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId");//.equalTo(userId);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.d("test", "onDataChange: "+postSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.wtf("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
EDIT 3: https://i.stack.imgur.com/iBkcx.png
Firebase Realtime database does not allow you to chain multiple filter methods. If you want to get the records where : userId="1057...", please change the following line of code:
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
with
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId").equalTo(1057...);
If you want to get all the records where banknoteType ="100_dollar" and userId="1057...", please see my answer from this post.
According to your edited post, please also change this line of code:
Log.d("test", "onDataChange: "+postSnapshot);
to
Log.d("test", "onDataChange: "+postSnapshot.child("userId").getValue(String.class));
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);
I have two nodes Users and Plants
Users
|
|-plantId
|
|-image
|
|-imageLink
|-plantId
|
|-image
|
|-imageLink
Plants
|-plantId
|
|-collectedPlant
|
|-plantCount
The plantid in users and plants will be same. I need to get a HashMap containing plant id-imagelink and plantCount.
I have the two nodes data separately with me. Is there a simple way to solve it?
To solve this according to the edited database structure and assuming that the plantCount property is defined as a Long, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference imageRef = rootRef.child("Users").child("plantId").child("image");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String imageLink = ds.child("imageLink").getValue(String.class);
DatabaseReference collectedPlantRef = rootRef.child("Plants").child("plantId").child("collectedPlant");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Long> map = new HashMap<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
Long plantCount = dSnapshot.child("plantCount").getValue(Long.class);
map.put(imageLink, plantCount);
}
//Do what you want with this Map.
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
collectedPlantRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
imageRef.addListenerForSingleValueEvent(valueEventListener);
As you can see, I have used nested queries in order to get the Map that you are looking for.