I have 2 layer structure of table inside my Firebase. I have problem with retrieving this. How can I retrieve this data from my Firebase? I have provided my main code and my Order class.
here is my code
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
orderList = new ArrayList<>();
for (DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
orderList.add(orderSnapshot.getValue(Order.class));
}
psOrderAdapter PsOrderAdapter = new psOrderAdapter(orderList);
recyclerView.setAdapter(PsOrderAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ManageOrder.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
public class Order {
public String cust_id;
public String pro_id;
public String total;
public String name;
public String address;
public String phone;
public String status;
public String date;
public String dateTime;
public Order() {
}
public Order(String cust_id, String pro_id, String total, String name, String address, String phone, String status,String date, String dateTime) {
this.cust_id = cust_id;
this.total = total;
this.name = name;
this.address = address;
this.phone = phone;
this.pro_id = pro_id;
this.status = status;
this.date=date;
this.dateTime=dateTime;
}
//getter and setter
}
I'm expecting a result a result like this
Try the following:
for(DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : orderSnapshot.getChildren()) {
orderList.add(ds.getValue(Order.class));
}
}
Add another for loop to be able to retrieve the data.
Related
So i have problem regarding adding the appointment details in my firebase android studio. I want the user to store their appointment details in appointment database and I also want to check if the user has booked the date and day. However , after the user has pressed the confirm button, it doesnt store the appointment details in the firebase and it also doesnt prompt the dialog message to the user indicating that their appointment has been registered successfully? Is there any way to solve this problem ? The code is shown as below :
private void addAppointment() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("idPatient", FirebaseAuth.getInstance().getCurrentUser().getUid());
hashMap.put("idDoctor", idDoctor);
hashMap.put("time", time.getText().toString());
hashMap.put("date", day.getText().toString());
hashMap.put("status", "On hold");
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Appointment");
reference1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot data : snapshot.getChildren()) {
Appointment relationship = data.getValue(Appointment.class);
if (relationship.getTime().equals(time.getText().toString()) && relationship.getDate().equals(day.getText().toString()) && relationship.getIdDoctor().equals(idDoctor)) {
new SweetAlertDialog(BookAppointmentActivity.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("The date and time has been booked")
.show();
}else if(snapshot.exists()){
reference.child("Appointment").push().setValue(hashMap);
new SweetAlertDialog(BookAppointmentActivity.this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Congratulations")
.setContentText("Your appointment is registered successfully")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
Intent intent = new Intent(BookAppointmentActivity.this, MainActivity.class);
startActivity(intent);
}
})
.show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Also check the firebase rules, read and write are set to true as per your requirements
so first of all you can create a modal class for all the children (example - doctor, time, status )
package com.example.chatapp;
public class UserModel {
String name;
String phone;
String about;
String url;
String uid;
public UserModel(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
then declare this modal class
Usermodal modal = new Modal class
then insert data like
modal.setname(yourdata);
then write
databaseref.child(key).setvalue(modal);
you can refer to this link for more.
I'm trying to load an object from my database but the dataSnapshot is not returning anything. I have a structure like this:
This is my Event object:
public class Event implements Serializable {
private String eventName, eventDescription;
private Author author;
private Venue venue;
private ArrayList<Comment> comments;
private ArrayList<Like> likes;
public Event() {
}
public Event(#NonNull String eventName, String eventDescription, Author author, Venue venue) {
this.eventName = eventName;
this.eventDescription = eventDescription;
this.author = author;
this.venue = venue;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public String getEventDescription() {
return eventDescription;
}
public void setEventDescription(String eventDescription) {
this.eventDescription = eventDescription;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(ArrayList<Comment> comments) {
this.comments = comments;
}
public List<Like> getLikes() {
return likes;
}
public void setLikes(ArrayList<Like> likes) {
this.likes = likes;
}
}
And this is my code:
Event event;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("Event").child("0").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
event = dataSnapshot.getValue(Event.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The event object comes back as null even though I'm pretty sure the path is correct
I developed a login app in Java where the user can login using their emailaddress and password. This works fine so far, but I have the problem that my UserModel.java is null when I get to my home activity. This also makes sense to me since Firebase Auth only checks the email and password and does not select the relevant information from the realtime database. I have therefore inserted a datasnapshot, this also works in the intended way since the system outputs the desired name.
My question is now how can I assign this datasnapshot to my UserModel so that my UserModel is no longer null (is it?!). In the last part of my HomeActivity you can see a String which should contain the Users Name, however even if I log in with an existing account this String is only showing the "Example Name". Due to the fact that the system is printing out the correct name I believe the DataSnapshot works as it should.
Thanks for your help!
part of my HomeActivity
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
final FirebaseDatabase database =FirebaseDatabase.getInstance();
DatabaseReference myref=database.getReference("Users").child(firebaseAuth.getUid());
myref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserModel userModel= dataSnapshot.getValue(UserModel.class);
System.out.println(userModel.getName());
currentUser=userModel;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(HomeActivity.this, ""+databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
if(currentUser!=null) {
Common.setSpanString("Hey, ", currentUser.getName(), txt_user);
}
else{
UserModel userModel = new UserModel(uid,name,address,phone,email,password);
userModel.setName("Example Name");
Common.setSpanString("Hey, ", userModel.getName(), txt_user);
}
UserModel
private String uid, name, address, phone, email, password;
public UserModel() {
}
public UserModel(String uid, String name, String address, String phone,String email,String password) {
this.uid = uid;
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
this.password = password;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() { return password; }
public void setPassword(String password) {
this.password = password;
}
}
part of my Common class
public static UserModel currentUser;
I have now put both parts of the code together and was able to display the string with the correct name. However, the Common.CurrentUser is not initialized what is not a problem as long as the Attributes are alright.
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
if(firebaseAuth.getCurrentUser()!=null) {
final FirebaseDatabase database =FirebaseDatabase.getInstance();
DatabaseReference myref=database.getReference("Users").child(firebaseAuth.getUid());
myref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserModel userModel= dataSnapshot.getValue(UserModel.class);
System.out.println(userModel.getName());
Common.setSpanString("Hey, ", userModel.getName(), txt_user);
currentUser=userModel;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(HomeActivity.this, ""+databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
}else{
UserModel userModel = new UserModel(uid,name,address,phone,email,password);
userModel.setName("Example Name");
Common.setSpanString("Hey, ", userModel.getName(), txt_user);
}
My database structure is like this:
users
8aWcF6GQmpezfJkVnW5uYoJ2wtI3
email: "jack"#mail.com"
height: "180cm"
imgUrl: "https://www.goldennumber.net/wp-content/uploads..."
matches
WEZ36bsEFXQtrJWQJVT3KMtsgQC3: true
8oqmrMVZ57XXlunIAUEeBgKFZ0h2: true
uid: "8aWcF6GQmpezfJkVnW5uYoJ2wtI3"
username: "jack"
I am trying to convert this structure to this object:
public class UserMatchDTO {
private String uid;
private String username;
private String height;
private String imgUrl;
private String email;
private HashMap<String, Boolean> userMatches = new HashMap<>();
public UserMatchDTO() {
}
public UserMatchDTO(String uid, String username, String height, String imgUrl, String email, HashMap<String, Boolean> userMatches) {
this.uid = uid;
this.username = username;
this.height = height;
this.imgUrl = imgUrl;
this.email = email;
this.userMatches = userMatches;
}
public String getUid() {
return uid;
}
public String getUsername() {
return username;
}
public String getHeight() {
return height;
}
public String getImgUrl() {
return imgUrl;
}
public HashMap<String, Boolean> getUserMatches() {
return userMatches;
}
public void setUserMatches(HashMap<String, Boolean> userMatches) {
this.userMatches = userMatches;
}
public String getEmail() {
return email;
}
}
Here is the method where I convert this to my object:
final List<UserMatchDTO> userMatchDTOs = new ArrayList<>();
databaseReference.child("users").addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
userMatchDTOs.add(userMatchDTO);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
However, when I debug this, the userMatches HashMap is always size 0. So why child "matches" from "user" is not converted to HashMap?
Here is what the snapshot looks like:
DataSnapshot { key = 8oqmrMVZ57XXlunIAUEeBgKFZ0h2, value = {email=jack#mail.com, height=180cm, uid=8aWcF6GQmpezfJkVnW5uYoJ2wtI3, imgUrl=https://www.goldennumber.net/wp-content/uploads/2013/08/florence-colgate-england-most-beautiful-face.jpg, username=jack, matches={WEZ36bsEFXQtrJWQJVT3KMtsgQC3=true, 8oqmrMVZ57XXlunIAUEeBgKFZ0h2=true}} }
Ok, so i manage to solve this, but I am not sure if this is good solution.
I just map the response to Object first and then cast this to the HashMap.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
Object object = matchSnapshot.child("matches").getValue();
if(object != null){
userMatchDTO.setUserMatches((HashMap<String, Boolean>) object);
}
userMatchDTOs.add(userMatchDTO);
}
Is any better solution for this?
I want to create a function that iterates through a firebase structure looking like this:
{
"users":{
"7e122736-2dd4-4770-a360-a0e7cbe41a43":{
"currentLatitude":46.6598714,
"currentLongitude":23.5637339,
"displayName":"gjsj2",
"email":"2#vlad.com",
"password":"123"
},
"a09e7e1d-ad3a-4d21-b0ba-069e0999bb93":{
"currentLatitude":47.6599014,
"currentLongitude":23.5636797,
"displayName":"gjsj",
"email":"1#vlad.com",
"password":"123"
},
"abc29286-fd6d-4088-95da-759828b5835d":{
"currentLatitude":50.6599043,
"currentLongitude":23525.5637188,
"displayName":"gjsj3",
"email":"3#vlad.com",
"password":"123"
}
}
}
I want to create a function that takes every unique user id's child and uses his coordinates to create a marker on a google maps map. Here's what i got so far but it doesnt seem to be working :
public void onChildChanged(DataSnapshot snapshot, String s) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
for (DataSnapshot uniqueUserSnapshot : userSnapshot.getChildren()) {
Users currentUser = uniqueUserSnapshot.getValue(Users.class);
MarkerOptions options = new MarkerOptions()
.title(currentUser.getEmail())
.icon(BitmapDescriptorFactory.defaultMarker(getRandomNumberInRange(0, 360)))
.position(new LatLng(currentUser.getCurrentLatitude(), currentUser.getCurrentLongitude()));
mMap.addMarker(options);
Toast.makeText(MainActivity.this, "fsafasfasfas", Toast.LENGTH_SHORT).show();
}
}
}
And here's my Users POJO:
package com.licenta.vladut.mmap;
public class Users {
String email;
String displayName;
String password;
double currentLatitude;
double currentLongitude;
public Users() {
}
public Users(String email, String displayName, String password, double currentLongitude, double currentLatitude) {
this.email = email;
this.displayName = displayName;
this.password = password;
this.currentLongitude = currentLongitude;
this.currentLatitude = currentLatitude;
}
public Users(String email, String displayName, String password) {
this.email = email;
this.displayName = displayName;
this.password = password;
}
public String getDisplayName() {
return displayName;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public double getCurrentLongitude() {
return currentLongitude;
}
public double getCurrentLatitude() {
return currentLatitude;
}
}
If I understand the question correctly, you are actually close to what you want to do. Reference the database child user, and then add a ValueEventListener:
Firebase userRef = new Firebase(/*url*/);
userRef = userRef.child("users");
userRef.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot uniqueUserSnapshot : dataSnapshot.getChildren()) {
...
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
ValueEventListener returns the node called, not children one by one.