How to query all data in firebase realtime? - android

I want to compare text with data from firebase. Below is my code and it reads name only from ing01. but actually i want it to read from all ingredient data, not only ing01. Please help me, thank you.
final String dataCompare=sb.toString();//.replaceAll("\\s+","");
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");//.child("ing01").child("iName");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
String iName = ds.child("iName").getValue(String.class);
if(dataCompare.equals(iName)){
mResultEt.setText(dataCompare);
mStatusEt.setText("OK");
mStatusEt.setTextColor(Color.GREEN);
}
else{
mResultEt.setText(dataCompare);
mStatusEt.setText("Not OK");
mStatusEt.setTextColor(Color.RED);
}
}

Check this:
FirebaseDatabase.getInstance().getReference().child("ingredients").addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String iName = childSnapshot.child("iName").getValue(String.class);
//Implement your logic here
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
Here you will get all the ingredients and through iteration you get the iName.
But According your implementation logic. It's useless to get all the ingredients, rather you can get the specific ingredient matching your compare query. Try like below:
FirebaseDatabase.getInstance().getReference().child("ingredients").orderByChild("iName").equalTo(dataCompare).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()) {
mResultEt.setText(dataCompare);
mStatusEt.setText("OK");
mStatusEt.setTextColor(Color.GREEN);
} else {
mResultEt.setText(dataCompare);
mStatusEt.setText("Not OK");
mStatusEt.setTextColor(Color.RED);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);

Instead of firebaseDatabase.getInstance().getReference().child("ingredients").child("ing01").child("iName");, use firebaseDatabase.getInstance().getReference().child("ingredients"); for getting all ingredients

you can used a third party library like: Angularfire here is there official link: https://github.com/angular/angularfire

final String dataCompare=sb.toString();
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String iName1 = dataSnapshot.child("ing01").child("iName");
String iName2 = dataSnapshot.child("ing02").child("iName");
//now here you can compare both the iName values with the dataCompare object.
}
}
**** EDIT ****
final String dataCompare=sb.toString();
Log.d("DataCompare: ", dataCompare);
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildren() == null) {
Log.d(TAG, "onDataChange: snapshot has no children");
} else {
int i = 1;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String iName = ds.child("ing0" + i++).child("iName").getValue();
// if this doesn't work try this --
// String iName = ds.child("iName").getValue();
Log.d(TAG, "name value: " + iName);
if (iName.equals(dataCompare)) {
Log.d(TAG, "onDataChange: string equals");
} else {
Log.d(TAG, "onDataChange: strings are not equal");
}
}
}
}
}
Inside the onDataChange() method I wrote :-
String iName = ds.child("ing0" + i++).child("iName").getValue();
here we are reading the child "ing01" (in the first iteration of the loop) of the datasnapshot which is currently at "ingredients", and then we read "iName" and its value into iName string object.
for each loop will do this for all the children of the dataSnapshot which means for all the data you have in your firebase database.

Related

How to read data from RecyclerView and make comparison?

Hi I want to read the display data from RecyclerView and make comparison.
This my layout for the activity:
What I want to do is to read all data from RecyclerView and compare with Daily Calorie Suggestion.
After reading all data, I need to make comparisons on how many times the user have taken above, less or sufficient total calories as shown in the "Analysis of Total Calories Consumed of Last 7 Days"
The code:
#Override
protected void onStart() {
Query query = ref.orderByChild("timeStamp").limitToLast(7).endAt(Date);
super.onStart();
if (query != null) {
query .addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userHighlights = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userHighlights.add(ds.getValue(HighightsModel.class));
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()));
int daily_calorie = Integer.parseInt(userCalorieSuggestion);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
HighlightsAdapter highlightsAdapter = new HighlightsAdapter(userHighlights);
highlightsRV.setAdapter(highlightsAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UserNewHighlights.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
This is my firebase:
Do I have to write a new code to solve this problem or else? Any help will be much appreciated. Thanks
As #MasoudDarzi mentioned, it's not related to the RecyclerView.
You can try something like this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userHighlights = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userHighlights.add(ds.getValue(HighightsModel.class));
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()));
int daily_calorie = Integer.parseInt(userCalorieSuggestion);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
HighlightsAdapter highlightsAdapter = new HighlightsAdapter(userHighlights);
highlightsRV.setAdapter(highlightsAdapter);
// do calculation here with userHighlights
int countExceeded = 0, countBelow = 0, countSufficient = 0;
for (HighightsModel h : userHighlights) {
if (h.totalCalorie > daily_calorie) {
countExceeded++;
} else if (h.totalCalorie < daily_calorie) {
countBelow++;
} else {
countSufficient++;
}
}
// update your TextView with the count numbers
// todo
}
}
so The brute force solution is to have a for in your data after getting the 7 days average.
for (your 7 days data){
// check if your data is lower or higher than the average
// and store number of higher or lower
}
looking for a better solution?
I have solved my problem by adding another child at History node. Whereby, previously I have only these for History :
but I add new child which is called STATUS, the status is updated from previous activity as seen the pic below:
so what I did for the code is :
private void upDateAnalysisAbove() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("ABOVE").limitToLast(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = String.valueOf(dataSnapshot.getChildrenCount());
int values = Integer.parseInt(value);
txt_above_output.setText(values + " times(s)");
upDateAnalysisLess(values);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//LESS
private void upDateAnalysisLess(int values) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("LESS").limitToFirst(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valueLess = String.valueOf(dataSnapshot.getChildrenCount());
int values_Less = Integer.parseInt(valueLess);
if (values_Less == 0){
txt_less_output.setText(values_Less + " times(s)");
}
if (values > values_Less){
int finalCount = values - values_Less ;
txt_less_output.setText(finalCount + " times(s)");
}
if (values <values_Less){
int finalCount = values_Less - values ;
txt_less_output.setText(finalCount + " times(s)");
}
updateSuff();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SUFFICIENT
private void updateSuff() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("SUFFICIENT").limitToFirst(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = String.valueOf(dataSnapshot.getChildrenCount());
int suffValue = Integer.parseInt(value);
if (suffValue == 0) {
txt_sufficient_output.setText(suffValue + " times(s)");
}
if (suffValue != 0){
txt_sufficient_output.setText(suffValue + " times(s)");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Here is the output:
credit to this post that helped me a lot, and thanks for those who tried to help me.

How to successfully calculate value from a child in firebase database

I am trying to calculate the sum of value of all children in the databse with the name "Price"
below is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mtotal = (TextView) findViewById(R.id.textre);
mda = FirebaseDatabase.getInstance().getReference().child("Cart");
mda.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object price = map.get("Price");
int pvalue = Integer.parseInt(String.valueOf(price));
sum += pvalue;
if (sum<100){
Toast.makeText(getApplicationContext(),"greare",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"sorry",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
as shown in my code if the value obtained from the price nodes is less than 100 then a toast message should appear saying "success". Instead, the app crushes with no message
the image is a view of my firebase database showing the values "Price" I wish to obtain
Try doing this, I think that you are not getting the Price value right
mda.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
int pvalue = ds.child("Price").getValue(Integer.class);
sum += pvalue;
if (sum<100){
Toast.makeText(getApplicationContext(),"greare",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"sorry",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});

Can't get value from Firebase Database DataSnapshot

I have read many answers to this question, none solved my problem.
ValueEventListener dataListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
DataSnapshot ls = ds.child("/leafBox001");
DataSnapshot cs = ls.child("/currentState");
Log.i(TAG, "msg " + cs + ls + ds);
}
Log returns the following:
DataSnapshot { key = leafBox001, value = {lightSensor=6793, currentState=false} }
DataSnapshot { key = currentState, value = null }
DataSnapshot { key = leafBox001, value = null }
As you can see, when I try to access a child the values become null.
I also always get null when using getValue. Example of that code:
ValueEventListener dataListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
currentState = ds.child("/leafBox001").child("/currentState").getValue(Boolean.class);
Log.i(TAG, "msg " + cs + ls + ds);
}
I have tried every variation of the above code, always null.
RTD Structure
Your database structure is like this:
leafBox001
lightSensor:6793
currentState: false
then do the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("leafBox001");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String sensor = dataSnapshot.child("lightSensor").getValue().toString();
String currentState = dataSnapshot.child("currentState").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The snapshot is at the key leafBox001 then you will be able to access the child of that key.

Retrieve parent and children of firebase field

I am trying to get a parent value of a field in Firebase database along with its children.
for clarification:
I want to loop through the Snapshot to find the user who want to login by his or her ID, after that I want to get the parent of that id (i.e. is the user female or male) after that I want to get the canton and name.
so what I am doing is:
database=FirebaseDatabase.getInstance();
rootRef = database.getReference();
users = rootRef.child("Users");
and then
users.orderByChild("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getValue().equals(curUser.getUid())) {
String gender = child.getKey().toString();
currentPolUser.setuGender(gender);
currentPolUser.setuName(child.child("Name").getValue().toString());
Log.d("FirebaseUsers", "SUCCESSSSSS: "+currentPolUser.getuName() + " " + currentPolUser.getuGender());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is child.getValue() returns an object that can't be compared to the User id string.
Try this:
ref.child("Users").orderByChild("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String gender = child.getKey();
for(DataSnapshot finalChild : child.getChildren()){
if (finalChild.getKey().equals(curUser.getUid())) {
HashMap<String, Object> map = (HashMap<String, Object>) finalChild.getValue();
String name = (String) map.get("name");
currentPolUser.setuGender(gender);
currentPolUser.setuName(name);
Log.d("FirebaseUsers", "SUCCESSSSSS: "+currentPolUser.getuName() + " " + currentPolUser.getuGender());
Log.e("TTT", name);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Firebase Query get values

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.

Categories

Resources