how to search a data from firebase for android - android

I want to search a condition ,if student studied at 'swe' department then i will show name and id for every student who are studied at swe department.
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("user");
databaseReference.orderByChild("department").equalTo("swe").addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String str = dataSnapshot.child("department").getValue(String.class);
Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

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.
Your current code fails to handle the fact that the result is a list. To solve this, loop over dataSnapshot.getChildren():
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("user");
databaseReference.orderByChild("department").equalTo("swe").addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String str = dataSnapshot.child("department").getValue(String.class);
Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
}
}

Related

Getting Firebase child key under random key

I want to retrive division and rno from for all key in array and compare those values in array with two other strings. how to do that?
You can get all children. try below code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
String rno = ds.child("rno").getValue().toString();
String div = ds.child("division").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I don't understand your question. But you can play on those who fulfill the requirements of the child and fulfill the conditions.
DatabaseReference roomRef = dbRef.child("Everybody Room List Messages");
ValueEventListener roomEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dsKey : dataSnapshot.getChildren()) {
for (DataSnapshot dsNick : dsKey.getChildren()) {
if (dsNick.child("nick").getValue().toString().equals(Nick)) {
dsNick.child("image").getRef().setValue("");
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
roomRef.addListenerForSingleValueEvent(roomEventListener);
UPDATE
So, if I understand, you need this code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot item: dataSnapshot.getChildren()) {
String snapDiv = item.child("division").getValue().toString();
String snapRno = item.child("rno").getValue().toString();
if(snapDiv.equals(divi) && snapRno.equals(roll)){
//Here you can do everythings you need because division and rno value are those you are searching.
}
}
}
});
I can't understand completly your question.
You need to retrieve for each child his division and rno value. After that you need to compare them with other variables. But in the session these variables are 2 and fixed or you need to compare with a list of pairs?
After that, assuming that the above question will be clarify, if strings are matches, you need to update the value of sub1, sub2,...,sub5 fields?
Please, give us more informations to understand your situation and give you more support.

Display data from multiple nodes in Firebase Android

Hi I am trying to display data from multiple nodes in my database on a listview.
What I'm trying to do is display the "detailCategory" and "detailValue" for every type of workout, every time its saved.
Here is the database reference i'm currently using for my app.
currentUserDB = FirebaseDatabase.getInstance().getReference("WorkoutDetails").child("Cardio").child(currentUId);
I know this needs to increment into the further nodes, but i'm not sure how to read from multiple nodes from at one time.
I'm using dataSnapshot to read the data. I have data being read by specific date in another page, using the code below. So the problem might just be with the database reference in this case.
#Override
protected void onStart() {
super.onStart();
currentUserDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
cardiosList.clear();
for(DataSnapshot cardioHistorySnapshot : dataSnapshot.getChildren()){
Cardio cardio = cardioHistorySnapshot.getValue(Cardio.class);
cardiosList.add(cardio);
}
CardioHistoryList adapter = new CardioHistoryList(Cardio_History.this, cardiosList);
ListViewCardioHistory.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
As I saw in your comment, that you are "going as far as the date node", according to this, to display the detailCategory and the detailValue, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dateRef = rootRef.child("WorkoutDetails").child("Cardio").child(currentUId).child(date);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String detailCategory = ds.child("detailCategory").getValue(String.class);
String detailValue = ds.child("detailValue").getValue(String.class);
Log.d("TAG", detailCategory + " / " + detailValue);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
dateRef.addListenerForSingleValueEvent(eventListener);
Where the date is the date under the currentUId, which can be 1-3-2018, 2-3-2018 and so on. And as you can see, to achieve this, we needed to use nested queries.

Firebase query in tree with depth and multiple children

I have a problem regarding querying the firebase database using a value and getting the specific node. My schema is shown here:
In my schema 'workLocations' belongs to an 'excavationWorks', and 'excavationWorks' belongs to an 'excavationLists'.
That means that the path to a specific workLocation is excavationLists/excavationWorks/workLocations/(specific workLocation)
The problem that I have is that I want to query the workLocations node by the location value (let's say London) and get the parent node (the red circled key which is the key of the specific workLocation).
I have search and read many posts but I haven't managed to make it work.
My code looks like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("workLocations").orderByChild("location").equalTo("London");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot workLoc : dataSnapshot.getChildren()) {
// do something with the individual "issues"
Log.d(TAG, workLoc.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you
To achieve this, you need to query your database twice like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference workLocationsRef = reference
.child("excavationLists")
.child("excavationWorks")
.child("workLocations");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String key = ds.getKey();
Query query = workLocationsRef.child(key).orderByChild("location").equalTo("London");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String description = snapshot.child("description").getValue(String.class);
Log.d("description", description);
String partentKey = snapshot.getRef().getParent().getKey();
Log.d("partentKey", partentKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
workLocationsRef.addListenerForSingleValueEvent(valueEventListener);

How to get key value under a key?

I want to use the spinner to display the key which under specific username but unfortunately it returns nothing to the spinner. I used an array to store the key value which under the username.
Here's my database structure
Let's said I am rexyou0831 and I just want to retrieve the 2 usernames which under my username but my code return me nothing to the list. un is my current username variables. Please if you got any idea please share it with me thank you.
Hers' my code
db = FirebaseDatabase.getInstance();
cref = db.getReference("chat");
public ArrayList<String> retrieve()
{
final ArrayList<String> Student=new ArrayList<>();
cref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot c:dataSnapshot.getChildren())
{
if(c.getKey().equals(un)){
for(DataSnapshot d: dataSnapshot.getChildren()){
Student.add(d.getKey());
}
}else{
Student.clear();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return Student;
}
To get those usernames under your username, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("chat").child("rexyou0831");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = ds.getKey();
list.add(userName);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
Your out put will be: [gigi1212, mario123]
Note, that onDataChenge() is called asynchronous which means that is called even before you are adding those keys to the list. As a conslusion, you need to declare and use that list, inside onDataChenge(), otherwise is null.

How to search data in Firebase?

Bundle bundle = getIntent().getExtras();
String name = bundle.getString("name");
mValueView = (TextView) findViewById(R.id.textView);
mRef = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/Users");
com.google.firebase.database.Query query = mRef.child("Users").orderByChild("title").equalTo(name);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Map<String,Object> map = (Map<String, Object>) dataSnapshot.getValue();
//String Title = (String) map.get("title");
String Title = dataSnapshot.child("title").getValue().toString();
mValueView.setText(Title);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to show object title is same name value.
This is the Firebase database:
If you want to search title value only one time, without listening for updates, you can simply use :
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}});
Then if you get a reference to 'Users' you can do some logic with iteration, for example :
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
String title = (String) singleSnapshot.child("title").getValue();
//do your logic
}
There are two problems in your code:
you're specifying the child node Users twice
a query results a list of results, which your onDataChange doesn't handle
specifying the child node Users twice
mRef = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/Users");
// ^^^^^
Query query = mRef.child("Users").orderByChild("title").equalTo(name);
// ^^^^^
Easily fixed:
mRef = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/");
Query query = mRef.child("Users").orderByChild("title").equalTo(name);
I'm not sure why you use getReferenceFromUrl() to begin with. For most applications, this accomplishes the same is simpler:
mRef = FirebaseDatabase.getInstance().getReference();
a query results a list of results
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.
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
System.out.println(snapshot.getKey());
System.out.println(snapshot.child("title").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

Categories

Resources