This is my data structure:
Here I want to retrieve the Latitude and Longitude of the last item of Location child based on the id = "sd".
Here's the code:
Query query = mDatabase.child("Users").orderByChild("Id").equalTo(busId);
// busId = "sd"
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot user : dataSnapshot.getChildren()) {
Query lastItem = user.getRef().child("Location").orderByKey().limitToLast(1);
lastItem.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lat = dataSnapshot.child("Latitude").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
How can I do that? Thanks
Please use this code for Android:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String Id = ds.child("Id").getValue(String.class);
if(Id.equals("sd")) {
Query q = ds.child("Location").getRef().orderByKey().limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren()) {
Double latitude = child.child("Latitude").getValue(Double.class);
Double longitude = child.child("Longitude").getValue(Double.class);
Log.d("TAG", latitude + " / " + longitude);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
q.addListenerForSingleValueEvent(valueEventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
Related
I have a problem to do subtract calculation by retrieving data from a Child Nod. As you can see my layout below, what I want to do is to get Remaining Kcal value by calculating Daily Kcal value minus Total Kcal and display the Remaining Kcal to the TextView.
I suspected the calculation for the subtraction part (code below) is not working at all as I tried to put the remainingCount/remainingCalorie value into firebase but nothing happened.
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is relevant code to do this operation, whereby I need to retrieve "daily calorie' from User first, then I can do the substraction daily calorie (Required Kcal) - total calorie consume (Total Kcal) = Remaining Calorie (Remaining Kcal):
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//CALCULATE AND DISPLAY TOTAL CALORIE ACCORDING TO DATE
private void updateTotalCalorie(final String date_n) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(date_record);
nameRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double count = 0;
for (DataSnapshot foodTypeSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: foodTypeSnapshot.getChildren()) {
double foodCalorie = Double.valueOf(recordSnapshot.child("foodCalorie").getValue(String.class));
count = count + foodCalorie;
userTotalCalorie.setText((count +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("totalCalorie", count);
values.put("Date Consume", date_n);
final double finalCount = count;
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
updateRemainingKcal(finalCount);
}
});
}
}
Log.d("TAG", count + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is my firebase looks like - there is no node of RemainingCalorie at all at History node:
How can I solve this issue despite knowing the problem. I have tried several ways but nothing could help to solve this code problem.
I have solved my own problem. Thank you, finally did it. This is right code for those who have same problem in future:
private void updateRemaining(final int finalCount) {
userDatabase = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String user = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int dailyCalorie = Integer.parseInt(user);
int remainingCalorie = dailyCalorie-finalCount;
userRemainingCalorie.setText((remainingCalorie +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
this is the screen-shot
I want to make it store private string keyy, but it does not save, what happens? I tried it with textview if it shows the data.
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot nodo : dataSnapshot.getChildren()) {
String key = nodo.getKey();
Log.d("TAG", key);
keyy = key;
mSetting.setText(key); // yes, show data
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
myRef.addListenerForSingleValueEvent(eventListener);
mSetting.setText(keyy); // No,show data
I hope this solve your problem
List<String> keyList = new ArrayList();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot nodo : dataSnapshot.getChildren()) {
String key = nodo.getKey();
keyList.add(key);
}
done(keyList);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
myRef.addListenerForSingleValueEvent(eventListener);
public void done(List k)
{
//show keys here
}
Do like this
List<String> keyList=new ArrayList<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot nodo : dataSnapshot.getChildren()) {
String key = nodo.getKey();
Log.d("TAG", key);
/*Add all the keys to keyList here*/
keyList.add(key);
}
/*After the loop ends set the list of keys to textview like this*/
if (keyList.size()>0)
{
for (String s : keyList)
{
mSetting.setText(mSetting.getText().toString()+"\n"+s);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
myRef.addListenerForSingleValueEvent(eventListener);
This is my firebase-database.
Query lastQuery = databaseReference.child("rawlocations").child("12345678").limitToLast(1);
lastQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Double latt= (Double) dataSnapshot.child("lat").getValue();
Double lngg= (Double) dataSnapshot.child("lng").getValue();
LatLng location=new LatLng(latt,lngg);
});
In this database locations are updating for every 10 meters.Now i want to refer the very recently updated location?How can i refer this in my code?Anyone can help?
If you want to get the latitude and longiture of a single id, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference idRef = rootRef.child("raw-locations").child("12345678");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
double lat = ds.child("lat").getValue(Double.class);
double lng = ds.child("lng").getValue(Double.class);
Log.d("TAG", lat + " / " + lng);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
idRef.addListenerForSingleValueEvent(eventListener);
If you want all ids, you need to loop twice.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rawRef = rootRef.child("raw-locations");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
for(DataSnapshot dSnapshot : ds.getChildren()) {
double lat = dSnapshot.child("lat").getValue(Double.class);
double lng = dSnapshot.child("lng").getValue(Double.class);
Log.d("TAG", lat + " / " + lng);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rawRef.addListenerForSingleValueEvent(eventListener);
Try this, it works in my code and feth every value from my childs
mDatabase.child("raw-locations").child("12345678").addValueEventListener(new ValueEventListener() {
final List<String> lstItems= new ArrayList<String>();
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = (String) ds.getKey();
String values = (String) ds.getValue();
Log.e("Values",""+values );
lstItems.add(values );
}
also you can change this line
String values = (String) ds.getValue();
with this
String Latvalue = (String) ds.child("lat").getValue();
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.
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
}
});