I am trying to get weight and quantity from Cat1 where item_name, date and branch are same in Cat2 in Firebase Realtime DB. But I don't know how to check conditions for that.
JSON
"Cat1" : {
"-LBBWypuYLVn-aDYWK-N" : {
"branch" : "b1",
"date" : "28/Apr/2018",
"weight" : "46",
"item_name" : "item1",
"quantity" : "20"
},
"-LBBZKUlEJB-HdiKftoj" : {
"branch" : "b2",
"date" : "28/Apr/2018",
"weight" : "112",
"item_name" : "item2",
"quantity" : "16"
}
},
"Cat2" : {
"-LBBWQcC3acYk-OOiX3T" : {
"branch" : "b1",
"date" : "28/Apr/2018",
"item_name" : "item1",
"weight" : "2.7",
"quantity" : "20"
}
}
So far I have done the following:
mFishQuery = mFishRef.orderByChild("date").equalTo(mawStock.getDate());
// mFishQuery = mFishRef.orderByKey();//.equalTo(mawStock.getDate());
// Query fishWeight = mFishQuery.orderByChild("item_name").equalTo(mawStock.getItem_name()).getRef().orderByChild("quantity").equalTo(mawStock.getQuantity());
mFishQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mWeightF = (Double) dataSnapshot.child("fish_weight").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFishRef.child("date").equalTo(mawStock.getDate()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try the following:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Cat2");
ref.orderByChild("item_name").equalTo("item1").addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String date=datas.child("date").getValue().toString();
DatabaseReference refer=FirebaseDatabase.getInstance().getReference().child("Cat1");
refer.orderByChild("date").equalTo(date).addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//retrieve data
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
When you query, you can only use one child so one orderByChild() or orderByKey()
So, here you have the datasnapshot at child Cat2 then you query where item_name=item1 and you retrieve the date from the database.
Then you add a nested listener and do a query where date= date_retrieved, and retrieve the data of Cat1.
Basically, you just have to do enough itr.next() until the iterator is at the nth position (where n is the random number from nextInt()) and then you can simply get the Object you want with getValue(), the example below should show it well:
Solution to get random generated keys.
questionsRef = FirebaseDatabase.getInstance().getReference().child("questions").child("DE");
questionsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int questionCount = (int) dataSnapshot.getChildrenCount();
int rand = random.nextInt(questionCount);
Iterator itr = dataSnapshot.getChildren().iterator();
for(int i = 0; i < rand; i++) {
itr.next();
}
childSnapshot = (DataSnapshot) itr.next();
question = childSnapshot.getValue(Question.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Finally I solved the problem with the help of #Peter Hadad's answer with some modification in his answer.
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Cat1");
ref.orderByChild("item_name").equalTo("item1").addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas : dataSnapshot.getChildren()){
DatabaseReference refer=FirebaseDatabase.getInstance().getReference().child("Cat1");
refer.orderByChild("date").equalTo(date).addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (Datasnapshot ds : dataSnapshot) {
List<Datasnapshot> list = new ArrayList<>();
list.add(ds);
//compare data and apply logic
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Related
I'm using Firebase realtime database. Below is the structure
Problem Statement: Over a list of "Users", I need to delete child who's having coins = 0
So far I'm stuck here
DatabaseReference deleteRef = dbref.child("Users").child("coins");
Query deleteQuery = deleteRef.orderByValue().equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Any help will be appreciated :)
You need to order the list by the child coins like here:
DatabaseReference deleteRef = dbref.child("Users");
Query deleteQuery = deleteRef.orderByChild("coins").equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
i have problem to get exact childs from database and add it to the list of "teams". is that possible? i can't find proper way to solve this problem. please help me.
image of my actual database structure
i want to get only values of "2" and "3", just list of all teams without members. As a result of my solution im getting all elements from all children.
i have tried sth like this:
mDatabase.child("teams").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
teamList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
teamList.add(snapshot.getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Use this
mDatabase.child("teams").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
teamList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
teamList.add(snapshot.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Try this:
mDatabase = _firebase.getReference("teams");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot _dataSnapshot) {
teamList = new ArrayList < > ();
try {
GenericTypeIndicator < HashMap < String, Object >> _ind = new GenericTypeIndicator < HashMap < String, Object >> () {};
for (DataSnapshot _data: _dataSnapshot.getChildren()) {
HashMap < String, Object > _map = _data.getValue(_ind);
teamList.add(_map);
}
} catch (Exception _e) {
_e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError _databaseError) { }
});
I have number of Medicines corresponding to each patient unique key. i am facing trouble to retrieve all of medicine data of the patient Here is my database structure.
{
"Medicine" : {
"-LnRyr-3szcVYVtr_d4m" : {
"Med1" : {
"dosage" : "1+1+1",
"medname" : "Panadol",
"time" : "After Every Meal"
},
"Med2" : {
"Mmedname" : "Raisik",
"med2dosage" : "1+1+1",
"med2time" : "after every meal 1 week"
}
}
}
}
Code
databaseReference = FirebaseDatabase.getInstance().getReference("Medidine");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot requestSnapshot: dataSnapshot.getChildren()) {
DataSnapshot ds = requestSnapshot.child("Med1");
for (DataSnapshot medicinesnapshot: ds.getChildren()) {
String MedicineName = medicinesnapshot.child("medname").getValue(String.class);
String MedDosage = medicinesnapshot.child("dosage").getValue(String.class);
String medtime = medicinesnapshot.child("time").getValue(String.class);
marray.add(MedicineName+MedDosage+medtime);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
For a patient with patientId=-LnRyr-3szcVYVtr_d4m;
then you can get all medicines related to that patient like this
String patientId="-LnRyr-3szcVYVtr_d4m";
FirebaseDatabase.getInstance().getReference().child("Medicine").child(patientId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
MedicineData medicineData = snapshot.getValue(MedicineData.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I need to get the data which is the "2019-05-15". NOT the inside of the "2019-05-15". Also this is NOT the current date today.
"data"
{
"2019-05-03": {
"Name": "asdasdasd",
"Phone": "0934753423423"
},
"2019-05-15": {
"Name": "zxczxc",
"Phone": "8745837456038"
}
}
I tried the current date but im getting error of it. I just need the "2019-05-15" to get
myRef=FirebaseDatabase.getInstance().getReference().child("data");
Query query = myRef.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d("Date", dataSnapshot.child("").getValue().toString());
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User val", child.child("Name").getValue().toString());
Log.d("Date", dataSnapshot.child("").getValue().toString()); // What should I write here?
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Thanks in advance
Try the following:
myRef=FirebaseDatabase.getInstance().getReference().child("data");
Query query = myRef.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String key = child.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
First, add a reference to the parent node data, then using getKey() you will be able to retrieve the date.
FirebaseDatabase.getInstance().getReference("Block").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(myUID)){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(list.get(position).getUid())){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).child(list.get(position).getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getValue().equals("1")){
call_method();
}else{
//code...
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This code works well, but it is very long so I am asking for the best way to write it ?
I want to check firstly if Block node has child equals to my UID if it is true then I want to check if my UID has child equals to specific UID if it is true then I want to get the value of block which is 0 in this example
How can I do that ? Thank you very much.
Just traverse to the path specified using child. You will get no data if the path doesn't exist.
FirebaseDatabase.getInstance().getReference("Block")
.child("MyUUID")
.child("specificUUID")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
// ... Do something
} else {
call_method();
}
// ... Other code
}
Try this:
Firebaseuser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Block");
ref.child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exist()){
//checks first uid
if(dataSnapshot.hasChild(seconduid){
//checks if seconduid is there
for(DataSnapshot datas:dataSnapshot.getChildren()){
String blocks=datas.child("block").getValue().toString();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will check the first uid if(dataSnapshot.exist()) after that it will check if that uid node has the second uid that you provide if(dataSnapshot.hasChild(seconduid){ then you will iterate and get the node block