Firebase - (DataSnapshot with multiple child nodes user unique key ) -Null Object Refrence - java

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) {
}
});

Related

Iterate, Check for condition & delete accordingly : Firebase Realtime

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();
}
});

Firebase Database Not in Sync

I want to keep the addToCart button in sync with the Firebase database. The button should be enabled if the checkForActiveOrdersQuery has no children, otherwise, it should be disabled.
The issue with the below code is that the keepSynced(true) is not working.
checkForActiveOrders = FirebaseDatabase.getInstance().getReference("activeOrders");
checkForActiveOrdersQuery = checkForActiveOrders.child(restaurantID).child(tableID);
checkForActiveOrdersQuery.keepSynced(true);
checkForActiveOrdersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String orderIDKey = dataSnapshot1.getKey();
if (!dataSnapshot.hasChildren()) {
addToCartButton.setEnabled(true);
} else if (!orderIDKey.equals(orderID)){
addToCartButton.setEnabled(false);
} else if (orderIDKey.equals(orderID)) {
addToCartButton.setEnabled(true);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Data retrieving error while i want to get all child from a certain Key

I want to read some specific child from the parent-child, by getchild() function but this will not work properly.
FirebaseUser FUser = mAuth.getCurrentUser();
String userid = FUser.getUid();
DatabaseReference DR;
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid);
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I want to get this four child from every key.
you have to add your push id in reference :-
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid).child("push id");
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try like this if you just want to read the value. if you want to read data only once use addListenerForSingleValueEvent()
*Try to read values by object stucture https://firebase.google.com/docs/database/android/read-and-write#basic_write
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d: ds.getChildren()) {
//below line may cause null pointer Exception
String Height = d.getKey() + d.getValue() + "\n".toString();
if(d.child("1Height:").getValue()!=null){
String ch = d.child("1Height:").getValue(String.class);
//tv.append(Height);
tv.append(ch);}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
To get the value of your 4UserId property, simply use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("HistoryTable").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("4UserId").getValue(String.class);
Log.d(TAG, userId);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
2Wwrjx...P2obFO83

How to retrieve all Uid without currentUser?

I don't know how to retrieve all Uid. This is my data:
this is my snippet code to set the data:
reference = db.getReference("Attendance");
reference.child(id).child(uid).child.("Status").setValue(status);
any help thank you guys
To log all UIDs (and names) from the JSON:
reference = db.getReference("Attendance");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot idSnapshot: dataSnapshot.getChildren()) {
System.out.println(idSnapshot.getKey());
for (DataSnapshot userSnapshot: idSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey());
System.out.println(userSnapshot.child("Status/xname").getValue(String.class));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Retrieve cross objects child from Firebase Database

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) {
}
});

Categories