I try to get data from the database.
Code:
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("User")mDatabaseUsers.orderByChild("name").startAt("m");
mDatabaseUsers.keepSynced(true); mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> map = dataSnapshot.getValue(Map.class);
String name = map.get("name");
Toast.makeText(AddFriendActivity.this,nick.toString(),Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get all users with the letter m!
How does is work?
Thank you!
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 you'll need to loop over the results in dataSnapshot:
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.child("name").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Also see the brief example in the Firebase documentation on using a value event to get a list of results.
Related
So i have a viewholder which has the name of the user and Under it i wanna put the last message that this user received , i have a query that gives me the last node in the database there is my code :
Query lastQuery = allDb.child("ReceivedMessages").child(mCurrent_user_id).child(list_user_id).orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
friendViewHolder.lastMessage.setText(message);
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
and this is my database structure (also i'm sure that the referance is correct because whenever i assign all of the data to a textView it gives me the last node plus the message and date etc .. but i only want the message )
and this is my error
I hope this will do the job.
Query lastQuery = allDb.child("ReceivedMessages").child(mCurrent_user_id).child(list_user_id).orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnaphot.getChildren()) {
String message = ds.child("message").getValue().toString();
friendViewHolder.lastMessage.setText(message);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
can somebody help me with the valueeventlstener?
i have got this database structure in firebase
Categories
-KvxSVFRZIO3ENylF0id
color: "ff99ffff"
name: "Cars"
-KvxbiS-L6iALA7Os8q4
color: "fffffdd4"
name: "Movies"
now i want to get fffffdd4 in a string when the name Movies is given.
mkatcolordb.child("Categories").orderByChild("name").equalTo(item).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String areaName = dataSnapshot.child("color").getValue(String.class);
StyleableToast.makeText(NewThemaActivity.this, areaName, Toast.LENGTH_LONG, R.style.StyledToast).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This code doesnt work
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 code needs to handle this. The simplest way to do so for your code:
mkatcolordb.child("Categories").orderByChild("name").equalTo(item).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot colorSnapshot: dataSnapshot.getChildren()) {
String areaName = colorSnapshot.child("color").getValue(String.class);
StyleableToast.makeText(NewThemaActivity.this, areaName, Toast.LENGTH_LONG, R.style.StyledToast).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
I have an android application which does the following:
com.google.firebase.database.Query query = mUsersRef
.orderByChild(USER_TABLE_EMAIL)
.startAt(searchTerm)
.endAt(searchTerm + FirebaseConstants.SEARCH_ESCAPE);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot d = dataSnapshot;
getView().showSearchResults();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: something?
}
});
I was wondering what the simplest way to convert dataSnapshot into User objects was. Do I need to get returned json and do some form of conversion? or is there a better way?
You can convert your data snapshot into an object as shown below:
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapShot : dataSnapshot.getChildren()){
User user = snapShot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: something?
}
});
I implemented some kind of chat app using Firebase database. Everything is set and working. Now I am trying to implement functionality that after user name changes all his messages with new username. The Message structure looks like this:
I had success whit this code:
private void changeCurrentUserMessagesUserName(final String newUserName) {
mDatabase.child(RequestParameters.FB_CHILD_MESSAGES) //messages
.orderByChild(RequestParameters.FB_CHILD_USERS_UID) //messageUserUid
.equalTo(mUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
ChatMessage message = messageSnapshot.getValue(ChatMessage.class);
mDatabase.child(RequestParameters.FB_CHILD_MESSAGES) //messages
.child(message.getMessageNodeKey())
.child(RequestParameters.FB_CHILD_MESSAGES_USERS) //messageUser
.setValue(newUserName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//do nothing
}
});
}
But it smells, if there are 100 messages in Firebase that belongs to current user this code will make 100 request to Firebase to change "messageUser" node to every single message.
Anyone could help how to make just one request that?
The link Andre provided has the gist of it: by using a single multi-location update, you can send the entire update in one call. Here's the same approach in Java:
mDatabase
.child(RequestParameters.FB_CHILD_MESSAGES) //messages
.orderByChild(RequestParameters.FB_CHILD_USERS_UID)
.equalTo(mUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,Object> updates = new HashMap<String,Object>();
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
ChatMessage message = messageSnapshot.getValue(ChatMessage.class);
updates.put(
RequestParameters.FB_CHILD_MESSAGES+"/"+
message.getMessageNodeKey()+"/"+
RequestParameters.FB_CHILD_MESSAGES_USERS,
newUserName
);
}
mDatabase.updateChildren(updates);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
How can I get the
"Dancing in the dark"
from this snapshot if the snapshot does not exist:? I figure it must be saved in the snapshot somewhere. Please read inline code comments..
private void addListenerForSingleValueEvent(String streetAddress, StringBuilder targetAddress){
DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
firebase.child("catalog/trax").orderByChild("namn").equalTo("Dancing in the dark")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// do sowm work on existing data
} else {
// How can I get the "Dancing in the dark" from the snapshot?
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Application.getInstance(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
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. By listening to a value event you get all matching results in one snapshot, so you have to iterate over the children.
DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
firebase.child("catalog/trax").orderByChild("namn").equalTo("Dancing in the dark")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot item: snapshot.getChildren()) {
// In this loop item is the snapshot of a single item.
// This means we can get the namm of the item
System.out.println(item.child("namm").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Application.getInstance(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});