How to search data in Firebase? - android

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

Related

How to read only first child value in Android

I'm new to Firebase I wanted to know is there a way to only get the value of first child and insert it into my spinner in android. Ex:
Just like the image shown I wanted to retrieve only the name "slot x" instead of getting all the values of it. Is it possible to do so?
Sure thing, you can order and limit the number of child nodes retrieved with something like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference myRef = rootRef.child("path to your parent node");
Query query = myRef.orderByKey().limiToFirst(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String key = childSnapshot.getKey(); // "slot 1"
String status = childSnapshot.child("status").getValue(String.class); // "occupied"
...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

how to retrieve data from fire base and assign to a string

I have a database in fire-base. In that I have a child node named "item1", under item1 i have two values
name
prize
I want to retrieve the name of item1 and I want to put it in a string called "foodname". How can I do that?
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
Here I tried but did not find solution
String foodname; //this string should get the value as "diary milk"
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("menu").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//This will loop through all items. Add variables to arrays or lists as required
for (DatasnapShot snap : dataSnapshot.getChildren())
{
foodname = dataSnapshot.child("name").getValue().toString();
String prize = dataSnapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You can fetch each child individually like such. Or you can make use of a Model or a Hashmap to fetch all of the data and then fetch the data you would like based on the Key
Using below code you can get food name
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Retrieving any data from Firebase requires a correct database reference and eventListeners that can work for what you want.
To know more about eventListeners visit this link.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu").child("item1");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// this code will get only details from item1
foodname = dataSnapshot.child("name").getValue(String.class);
String price = dataSnapshot.child("prize").getValue(Integer.class);
//if you want details from multiple items, you have to loop over the child nodes like this
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodname = snapshot.child("name").getValue().toString();
String price = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How to fetch data from firebase database

I want to show all data into Recycleview but only first image load other are not
shown recycleviewList anybody have idea about this.
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("items");
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String getImage= (String) dataSnapshot.getValue();
String ConvertImage;
ConvertImage = getImage.replaceAll("\\[",
"").replaceAll("\\]","");
String[] items = ConvertImage.split(",");
List<String> list = Arrays.asList(items);
Log.e("list",list.toString());
for (String item : list) {
arraylist.add(item);
setImg(arraylist);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
To get all those link, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference itemsRef = rootRef.child("items");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String link = ds.getValue(String.class);
Log.d("TAG", link);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
itemsRef.addListenerForSingleValueEvent(eventListener);
The output will contain, all those links from your item node.
If you are able to retrieve all the links and still only one image loads, then check the xml layout of single list item of RecyclerView and make sure the height is wrap_content and NOT match_parent like this
android:layout_height="wrap_content"

how to search a data from firebase for 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();
}
}

Unable to get All child data in Firebase Database using a Map?

I am trying to display all child "name" located in my database tree. My Database tree I used the Map to do so:
GenericTypeIndicator<Map<String, Object>> m = new GenericTypeIndicator<Map<String, Object>>() {};
Map<String, Object> map = snapshot.getValue(m);
String username = (String) map.get("name");
displayName.setText(username);// Display the name
I am displaying all the data into a recyclerView. But for some reasons instead of getting all names(Eva, smith, princess), I am only one which is the lastest one created "princess" being displayed 3 times in my recyclerView layout(princess, princess, princess). Anyone has any idea what I am doing wrong?
Assuming that you have a node named users in which you have all those uid's, to get all those name, please use the code below. Is the easiest way to achieve this.
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userId = (String) dataSnapshot.getKey();
DatabaseReference userIdRef = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue();
Log.d("TAG", name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
Hope it helps.

Categories

Resources