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?
Related
I'm trying to set key (firebase key) to my java object TaskModel. But after using setter when I'm trying to retrieve data using getter. It is returning null.
Database Structure
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
taskModel.setTaskID(dataSnapshot1.getKey());
taskModel = dataSnapshot1.getValue(TaskModel.class);
Log.d("myadaptor", taskModel.getTaskID());
list.add(taskModel);
}
Please help me set key to my object!
TaskModel.java
public class TaskModel {
private String taskTitle;
private String dueDate;
private String taskDescription;
private String taskID;
public String getTaskID() {
return taskID;
}
public void setTaskID(String taskID) {
this.taskID = taskID;
}
public String getTaskTitle() {
return taskTitle;
}
public void setTaskTitle(String taskTitle) {
this.taskTitle = taskTitle;
}
public String getDueDate() {
return dueDate;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public TaskModel(String taskTitle, String dueDate, String taskDescription) {
this.taskTitle = taskTitle;
this.dueDate = dueDate;
this.taskDescription = taskDescription;
}
public TaskModel(){
}
}
Here in your old code, you are assigning ID to taskModel, after that you initializing taskModel as new object from dataSnapShot. And in dataSnapShot you have null as id. SO it is like overridden of id:
taskModel.setTaskID(dataSnapshot1.getKey());
taskModel = dataSnapshot1.getValue(TaskModel.class);
Update the position of line:
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
taskModel = dataSnapshot1.getValue(TaskModel.class);
taskModel.setTaskID(dataSnapshot1.getKey());
Log.d("myadaptor", taskModel.getTaskID());
list.add(taskModel);
}
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.
My firebase database looks likes this
The blue rectangle is the data I want to retrieve.
Modal class for the blue rectangle looks like this
public class TripToCompany implements Serializable {
String tripDate;
String companyName;
String vehicleNo;
boolean isFinished;
String firstPickUp;
String inTime;
ArrayList<EmpToCompany> emptoCompanyList;
public TripToCompany() {
}
public TripToCompany(String tripDate, String companyName, String vehicleNo, boolean isFinished, String firstPickUp, String inTime, ArrayList<EmpToCompany> emptoCompanyList) {
this.tripDate = tripDate;
this.companyName = companyName;
this.vehicleNo = vehicleNo;
this.isFinished = isFinished;
this.firstPickUp = firstPickUp;
this.inTime = inTime;
this.emptoCompanyList = emptoCompanyList;
}
public TripToCompany(String tripDate, String companyName, String vehicleNo) {
this.tripDate = tripDate;
this.companyName = companyName;
this.vehicleNo = vehicleNo;
this.isFinished = false;
this.inTime = "-";
this.emptoCompanyList = new ArrayList<>();
}
public String getTripDate() {
return tripDate;
}
public void setTripDate(String tripDate) {
this.tripDate = tripDate;
}
public String getCompany() {
return companyName;
}
public void setCompany(String companyName) {
this.companyName = companyName;
}
public String getVehicleNo() {
return vehicleNo;
}
public void setVehicleNo(String vehicleNo) {
this.vehicleNo = vehicleNo;
}
public boolean isFinished() {
return isFinished;
}
public void setFinished(boolean isFinished) {
this.isFinished = isFinished;
}
public String getFirstPickUp() {
return firstPickUp;
}
public void setFirstPickUp(String firstPickUp) {
this.firstPickUp = firstPickUp;
}
public String getInTime() {
return inTime;
}
public void setInTime(String inTime) {
this.inTime = inTime;
}
public ArrayList<EmpToCompany> getEmptoCompanyList() {
return emptoCompanyList;
}
public void setEmptoCompanyList(ArrayList<EmpToCompany> emptoCompanyList) {
emptoCompanyList = emptoCompanyList;
}
public void addEmpToCompanyList(EmpToCompany etc) {
if (emptoCompanyList.size() == 0) {
firstPickUp = etc.getCabInTime();
}
emptoCompanyList.add(etc);
}
}
I am fetching the data from firebase using the standard query. Here is the code
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();
DatabaseReference mRef = defaultDatabase.getReference("data");
Query query = mRef.child("toComp/" + companyId + "/" + fromDate + "/" + shiftTimeId + "/");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot ds) {
if (ds.exists()) {
System.out.println("exist");
for (DataSnapshot singleSnapshot : ds.getChildren()) {
TripToCompany trpObj = (TripToCompany) singleSnapshot.getValue(TripToCompany.class);
ArrayList<EmpToCompany>ee= trpObj.getEmptoCompanyList();
System.out.println("Company Name: "+trpObj.getCompany()); //successfully retrived
System.out.println("Employee Count: " + ee.size()); //unable to fetch it. Gives NullPointerException
}
} else {
System.out.println("error");
}
}
#Override
public void onCancelled(DatabaseError de) {}
});
I am able to get the remaining data successfully from firebase. The data in red rectangle is the ArrayList, and I am unable to fetch it(show in red rectangle in the image). I have printed in the console using Sysout and I am unable to get ArrayList data. It returns NullPointerException. How can I fetch that ArrayList in the TripToCompany Object?
To solve this, please change the following lines of code:
public void setEmptoCompanyList(ArrayList<EmpToCompany> emptoCompanyList) {
emptoCompanyList = emptoCompanyList;
}
to
public void setEmptoCompanyList(ArrayList<EmpToCompany> emptoCompanyList) {
this.emptoCompanyList = emptoCompanyList;
// ^
}
You should assign the value of the local emptoCompanyList variable to the member class (this) field, not to the same variable.
In your JSON case from the picture I see, you need to change this code:
ArrayList< EmpToCompany> emptoCompanyList;
to:
ArrayList< String> emptoCompanyList;
But if you want arraylist of EmpToCompany class, you need to show what you have inside the red rectangle for the keys 0 and 1 .... and I will help you :)
I'm trying to query a firebase database to check if the user exists so, I can log them in. But, a strange issue has blocked me completely:
Query Code
String email = emailEditText.getText().toString();
String password = emailEditText.getText().toString();
fbUsers.orderByChild("email").equalTo(email).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, User> usersHashMap = (HashMap<String, User>) dataSnapshot.getValue();
Map.Entry<String, User> firstEntry = usersHashMap.entrySet().iterator().next();
User foundUser = firstEntry.getValue();
Log.d("Login: ", foundUser.getEmail());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
User Class
public class User {
private String email;
private String password;
User() {}
public User(String email, String password) {
this.email = email;
this.password = password;
}
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;
}
}
The strange issue is that the compiler says ALL OK but, in the runtime environment, this exception is thrown at Log.d()
java.lang.ClassCastException: java.util.HashMap cannot be cast to
com.example.project.User
This code uses getChildren().iterator().next() to get a snapshot for the single query result.
fbUsers.orderByChild("email")
.equalTo(email).limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
if (iter.hasNext()) {
User foundUser = iter.next().getValue(User.class);
Log.d("Login: ", foundUser.getEmail());
} else {
Log.w("Login: ", "No match: " + email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
if (databaseError != null) {
Log.e("Login: ", "onCancelled: " + databaseError.getMessage());
}
}
});
Have you tried calling getValue(User.class) ?
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.