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.
Related
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) {
}
});
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"
I need to update few nodes in firebase data which is posted from the server end.Need to update the node "is_done" to 0/1 from the device end.I have tried with different solutions but all became futile i.e it is adding a different node outside the "schedule" node.
Code snippet I have tried
private void updatemultiplefirebasedata() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference reference = firebaseDatabase.getReference();
Query query = reference.child("schedule").child("22-12-2017").child("route").child("1").child("kid").child("21");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
Log.d("Keys",String.valueOf(d.getKey())); //returning all the keys
HashMap<String, Object> result = new HashMap<>();
result.put("is_done", "0");
reference.child(String.valueOf(d.getKey())).updateChildren(result); //update according to keys
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
That's because your database reference still points to the root of your tree. You should assign the desired path to that reference.
Also: You don't need Queries in order to access data directly. You can simply attach a listener to the Database Reference.
private void updatemultiplefirebasedata() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference reference = firebaseDatabase.getReference().child("schedule").child("22-12-2017").child("route").child("1").child("kid").child("21");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
Log.d("Keys",String.valueOf(d.getKey())); //returning all the keys
HashMap<String, Object> result = new HashMap<>();
result.put("is_done", "0");
reference.child(String.valueOf(d.getKey())).updateChildren(result); //update according to keys
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try this :
reference.child(d.getKey()).updateChildren(result);
remove String.valueOf from child because your key is integer and you are passing it as string so instead of pointing it to same child it will create new key with String "1"
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.
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();
}
});