How to retrieve the sibling node's value in firebase? - java

What I'm trying to do is to return the value of the key named class of the node named m1 with a sibling named name
Here's what my database looked like
Here's what my code looked like
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Medicines");
final Query userQuery = rootRef.orderByChild("name").equalTo(textView.getText().toString());
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
txt1.setText(myParentNode);
DatabaseReference childRef = FirebaseDatabase.getInstance().getReference().child(myParentNode);
childRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String class_ = dataSnapshot.getValue().toString(); txt2.setText(class_);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
However it just gave me error T.T

Try this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Medicines");
final Query userQuery = rootRef.orderByChild("name").equalTo(textView.getText().toString());
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
String class=datas.child("class").getValue().toString();
String name=datas.child("name").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
the datasnasphot is medicines then the query is orderByChild("name").equalTo(textView.getText().toString()); equal to the value that is in the textView.
String keys=datas.getKey(); this will get you the key can be m1 or m2 or m3 depending on the text that you retrieve from the textview.
Then the other two will retrieve the name and the class from the database that are under a specific key.

Try this:
Create a class called Medicine(If you don't already have one) and make it have two String variables name and class and create a constructor, getter and setter methods then use this method:
public String getClassOfMedicineById(String id){
final String medicineClass = "";
FirebaseDatabase.getInstance().getReference("medicine-handbook").child("Medicines")
.child(id)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Medicine medicine = dataSnapshot.getValue(Medicine.class);
medicineClass = medicine.get_class();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return medicineClass;
}
And then call it like:
getClassOfMedicineById("m1");
Oh and don't call your class getter method getClass(). I think there's a method in the Object class so it might interfere or something.

Related

using query in android studio for retrieving data from firebase

This is my data structure on firebase. I am trying to retrieving first entered data based on double query, but unable to see output.
Here is my code
CarNo = findViewById(R.id.etCar);
myref = FirebaseDatabase.getInstance().getReference("message").child("Member");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String CarNoEntered = CarNo.getText().toString().trim();
Query checkUser = myref.orderByKey().equalTo(CarNoEntered);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot Dsnapshot) {
if(Dsnapshot.exists()){
Query lastQ = myref.child(CarNoEntered).orderByKey().limitToFirst(1);
lastQ.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String CarNum = snapshot.child("carNo").getValue(String.class);
String CarNm = snapshot.child("carName").getValue(String.class);
String CarOwner = snapshot.child("owner").getValue(String.class);
String Address = snapshot.child("address").getValue(String.class);
String Mobile = snapshot.child("mobile").getValue(String.class);
String Email = snapshot.child("email").getValue(String.class);
String dt = snapshot.child("date").getValue(String.class);
String wd = snapshot.child("workDone").getValue(String.class);
}
else{
CarNo.setError("Data not Available");
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
else{
CarNo.setError("Data not Available");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
I see two problems: one just making the code more complex than needed, and one that doesn't work. I'll cover them in turn.
There is never a need to do orderByKey().equalTo(...), you can just use: child(...) for that.
So:
DatabaseReference userRef = myref.child(CarNoEntered);
You then don't even need to listen for the value, but can query for the child node with:
Query lastQ = userRef.orderByKey().limitToFirst(1)
This is now a query for the first child under CarNoEntered.
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So in your case lastQ returns a list of one result, and you need to handle that list in your onDataChange method, by looping over snapshot.getChildren():
lastQ.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot childSnapshot: snapshot.getChildren()) {
String CarNum = snapshot.child("carNo").getValue(String.class);
String CarNm = snapshot.child("carName").getValue(String.class);
String CarOwner = snapshot.child("owner").getValue(String.class);
String Address = snapshot.child("address").getValue(String.class);
String Mobile = snapshot.child("mobile").getValue(String.class);
String Email = snapshot.child("email").getValue(String.class);
String dt = snapshot.child("date").getValue(String.class);
String wd = snapshot.child("workDone").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});

How to retrieve parent key of newly added child from Firebase using java

I want to retrieve "7753400075_Canada_twinpalms_||_twinpalms_20170824001545_F5BA7F33AD51CE283332001BEC409A46" key, How to do so? Here is my code...
ref.addValueEventListener(new ValueEventListener() { //addListenerForSingleValueEvent
#Override
public void onCancelled(DatabaseError arg0) {
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object response = dataSnapshot.getValue();
System.out.println("read data :"+response);
}
});
ref.child("chatmessage").child("devicetoken").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
// Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// System.out.println("previousChildName :"+previousChildName);
}
}
});
Here is the Firebase database example:
I tried using child data snapshot method but did not worked. It returns all data. But i need to get only the new child added parent. Any help for this will be much appreciated.
To solve this, you need to filter your results. Assuming that chatmessage is a direct child of your Firebase database root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference deviceTokenRef = rootRef.child("chatmessage").child("devicetoken");
Query query = deviceTokenRef.orderByKey().limitToLast(1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);

how get value from Firebase

I am new in android and I want to get userIDS from Firebase Database, I've tried by using this but it returns null.
By using this code
Value of Constants.ARG_CHAT_GROUP_ROOMS=Groups and Constants.NEW_NODE=newGroup
private void getMYuid() {
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child(Constants.ARG_CHAT_GROUP_ROOMS).child(Constants.NEW_NODE)
.child(senderUid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Toast.makeText(ActivityChatView.this, "not exist", Toast.LENGTH_SHORT).show();
Log.e("151","ACV"+dataSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("139","ACV"+senderUid);
}
Database Structure is this
if you want the first one under 15052169227329_myGroupName_Hell By Anne: Your problem is that you forgot the node before "Constants.NEW_NODE"
private void getMYuid() {
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child(Constants.ARG_CHAT_GROUP_ROOMS).child("15052169227329_myGroupName_Hell By Anne").child(Constants.NEW_NODE)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Toast.makeText(ActivityChatView.this, "not exist", Toast.LENGTH_SHORT).show();
Log.e("151","ACV"+dataSnapshot);
}
// You can cast this object later but it seems that that is a string and not an array
Object yourRequiredObject = dataSnapshot.child("usersIDS").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("139","ACV"+senderUid);
}
As i see, it's not an array it's a String. To get the userIDS, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child(Constants.ARG_CHAT_GROUP_ROOMS).child(senderUid).child(Constants.NEW_NODE);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String usersIDS = dataSnapshot.child("usersIDS").getValue(String.class);
Log.d("TAG", usersIDS);
//Here you can split the usersIDS String by , (comma)
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
In which senderUid is the missing child. This child can have the value like 1505217176288_myGroupName_1 or other coresponding group names.

How to retrieve full List Of Objects from Firebase that contains another List of String in it?

I have stored some List of person objects on Firebase.I want to retrieve this full List into newList of person from database.The class perosn contains another List batch
My class person look like:
public class person {
public String name,sid;
public HashMap<String,String> batch;
public int cls;
}
The code I have used is:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference fDatabaseRoot = database.getReference("studentsList");
fDatabaseRoot.orderByChild("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot areaSnapshot : dataSnapshot.getChildren()) {
Map<String,person> td =
(HashMap<String,person>)areaSnapshot.getValue();
// arrayListStudent= (List<person>) td.values();
// Log.d("aaa1",arrayListStudent.toString());
}
//Log.d("aaa",arrayListStudent.toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Where am i getting wrong.Please give some hint and suggestions....
Here is the screenshot of my database structure:
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentsListRef = rootRef.child("studentsList");
Query query = studentsListRef.orderByChild("name");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String key1 = ds.child("batch").child("0").getValue(String.class);
String key2 = ds.child("batch").child("1").getValue(String.class);
Log.d("TAG", name + " / " + key1 + " / " + key2);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
In this way, you'll get the value of name and of both fields under batch.

Firebase data retrieve with singlechildevent

Here is my firebase data structure . The child "Tags" is a child of root.
final Query searchquery = mDatabase.child("Tags").orderByKey().limitToFirst(10).startAt(s.toString().toLowerCase()).endAt(s.toString().toLowerCase() + "\uf8ff");
searchquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String u = dataSnapshot.child("article_name").getValue(String.class);
Toast.makeText(MainActivity.this,":/ : "+u.toString(),Toast.LENGTH_LONG).show();
}catch (Exception tg){
Toast.makeText(MainActivity.this,tg.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get the value of child "article_name" . I used the code above . But it is returning null .
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tagsRef = rootRef.child("Tags");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String article_name = ds.child("article_name").getValue(String.class);
Log.d("TAG", tagsRef);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
tagsRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Blood Circulation
Dummy Article
Also don't forget to use names for the keys that does not contain any spaces. So you need to change blood circulation in blood_circulation or bloodCirculation

Categories

Resources