In my Firebase, I have a database for an app. Let's say this is my Firebase JSON:
{
"Users" :{
"User1":{
"City": "Genk"
}
,"User2":{
"City": "Hasselt"
}
,"User3":{
"City": "Genk"
}
,"User4":{
"City": "As"
}
,"User5":{
"City": "Genk"
}
}
}
Now what I want is an ArrayList with all the users with city Genk. How is this possible? I want to use this ArrayList to put the specific Users who live in the city Genk in a ListView.
I suggest you create another child from the root like "UsersCity", In that way you can just call this child and retrieve it to your listview. Here's what i did:
String key = mDatabase.child("post").push().getKey();
UserPost userPost = new UserPost(author,uid,setemoticon,postData,mDate,latlng);
Map<String, Object> postValues = userPost.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/post/" + key,postValues);
childUpdates.put("/user-post/" + uid + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
Here's the Json output for that :
{
"post" : {
"-KcGVPpS9CTWPNax61wf" : {
"authorName" : "Test 1",
"dateCreated" : {
"dateCreated" : 1486352395887
},
"postDescription" : "sample post",
"postEmotion" : 2130837658,
"userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
},
"user-post" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
"-KcGVPpS9CTWPNax61wf" : {
"authorName" : "Test 1",
"dateCreated" : {
"dateCreated" : 1486352395887
},
"postDescription" : "sample post",
"postEmotion" : 2130837658,
"userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
}
},
//This child node is for users where you'll want to get the $uid to use for creation of other child nodes.
"users" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
"fullname" : "Test 1"
}
}
}
I am just a newbie programmer and I know my answer is not the best but I hope it could help you out with your problem. :)
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
Related
I am trying to receive all the data from a firebase database, so I can place it into a Users class however I do not know how I will iterate through the entire database as I cannot interger (the i variable in the for loop) insert values into the child field.
My code is this:
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
String fullname = (String) dataSnapshot.child(userId).child("Fullname").getValue();
String country = (String) dataSnapshot.child(userId).child("Country").getValue();
String profilePicture = (String) dataSnapshot.child(userId).child("ProfilePicture").getValue();
String username = (String) dataSnapshot.child(userId).child("Username").getValue();
Toast.makeText(getApplicationContext(), "Testing with: " + fullname + country + profilePicture + username, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Count : (4) - " + dataSnapshot.getChildrenCount(), Toast.LENGTH_SHORT).show();
showProfiles(dataSnapshot);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Database:
{
"Users" : {
"4PdlTlv3qjZ3BmDvrJyUut9Fnq43" : {
"Country" : "xx",
"Fullname" : "hh",
"ProfilePicture" : "htm/o/Images%2FSearchAdapter%2F4PdlTlv3qjZ3BmDvrJyUut9Fnq43%2FProfilePicture%2FProfilePic_2019.03.06.10.47.54.jpg.jpg?alt=media&token=b647708e-c6d5-4b45-bef0-3dc40301b73a",
"Username" : "hmack001"
},
"COg4r4io9hezhFpmK3adPucUXA93" : {
"Country" : "spain",
"Fullname" : "nat",
"ProfilePicture" : "hcom/o/Images%2FSearchAdapter%2FCOg4r4io9hezhFpmK3adPucUXA93%2FProfilePicture%2FProfilePic_2019.03.06.19.14.17.jpg.jpg?alt=media&token=8620b321-5cef-42f0-a828-dbb7c37c8e7d",
"Username" : "nat"
},
"Tw1xRxViygNsLqrQiaaMAvAduIu1" : {
"Country" : "uk",
"Fullname" : "harvey\n",
"ProfilePicture" : "t.com/o/Images%2FUsers%2FTw1xRxViygNsLqrQiaaMAvAduIu1%2FProfilePicture%2FProfilePic_2019.03.03.05.26.35.jpg.jpg?alt=media&token=c290e75a-5f92-4271-bcb5-c644fe1b14ef",
"Username" : "RGB"
},
"vOxr1RoDqgWogKK1lp9pfpTHc6w2" : {
"Country" : "scotland ",
"Fullname" : "greg greg",
"ProfilePicture" : "ot.com/o/Images%2FSearchAdapter%2FvOxr1RoDqgWogKK1lp9pfpTHc6w2%2FProfilePicture%2FProfilePic_2019.03.04.12.30.22.jpg.jpg?alt=media&token=27b024cf-0691-4121-8a27-26acf101ebc2",
"Username" : "greg"
},
"xecUOPeyMcQaQrgkU9ouDgK90Ai1" : {
"Country" : "ggh",
"Fullname" : "Da apply ",
"ProfilePicture" : "2FProfilePic_2019.03.03.04.58.50.jpg.jpg?alt=media&token=f35854c2-3ff9-4d18-9f7a-10c13f066c68",
"Username" : "gg"
}
}
}
I am aware that there is no attempt in this code to retrieve information from all the users fields, I do not understand the logic behind iterating through the database as I dont see where I can do Item 1, Item 2 etc.
Use this
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
System.out.println(childSnapshot.getKey());
System.out.println(childSnapshot.child("Country").getValue(String.class));
}
Need to add a new node "Completed" under the parent which will eventually contain all the information from the node "Requests" at end of the ride.
So basically, I need to create node "Completed" first but its not adding it.
database
{
"Requests" : {
"iowpxU6WKUWpzWJyfssSoOVCPFj2" : {
".priority" : "f8118c3k3v",
"destination" : "221 Prince William St",
"details" : {
"driver" : "nYIAHSYimJMHbMkXqDt9PQ0U3Nf2",
"location" : "27 Horsfield St",
"request status" : "accepted",
"ridePrice" : 3.75,
"rideStatus1" : "arrived at pickup",
"rideStatus2" : "rider in vehicle",
"rideStatus3" : "destination bound",
"rideStatus4" : "arrived at destination",
"rider" : "iowpxU6WKUWpzWJyfssSoOVCPFj2",
"riderPaid" : "true"
},
"Users" : {
"Drivers" : {
"nYIAHSYimJMHbMkXqDt9PQ0U3Nf2" : {
"driver" : "nYIAHSYimJMHbMkXqDt9PQ0U3Nf2",
"email" : "driver#me.com",
"name" : "driver",
"password" : "whatever",
"phone" : "5551212",
"rates" : "0"
}
},
"Riders" : {
"iowpxU6WKUWpzWJyfssSoOVCPFj2" : {
"avatarUrl" : "",
"email" : "rider#me.com",
"name" : "rider",
"password" : "whatever",
"phone" : "5551313",
"rates" : "0",
"riderId" : "iowpxU6WKUWpzWJyfssSoOVCPFj2"
}
}
}
}
addNewNode
private void addNewNode() { // TODO: ........ NOT ADDING NEW NODE :-| ..........
Toast.makeText(this, "addNewNode", Toast.LENGTH_LONG).show();
DatabaseReference newNode = FirebaseDatabase.getInstance().getReference("Completed");
newNode.child(riderId).push().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(DriverTripDetail.this, "addNewNode: onDataChange", Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Any assistance on how I can fix this would be greatly appreciated.
The Firebase Database stores values at paths. If there is no value, the path does not exist.
Your code creates a reference to /Completed/$pushID. but doesn't set any value, so the path doesn't get created. Something like this will work, since it sets a value:
newNode.child(riderId).push().setValue(true)
Child1
Child1.1
Subchild1
Subchild 2
Child 1.2
Subchild 1
Subchild 2
If I need to retrieve child1.1 and 1.2 how do I get them in textview?, as their subchild can be retrieved easily using datasnapshot.
I dont have enogh reputation to post image so have to type the structure of my firebase project. Hope my problem is understandable.
Code What i done is...
LoggedInRef.child(number).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null) {
if (sampleList != null) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
/* msg_List_Item msgLIST=ds.getValue(msg_List_Item.class);
msgList.add(msgLIST);*/
Log.d("MESSAGES<<<<<<<<", ds.getValue().toString() + "<<<<<<<<<<<<<<<<<<<<<<<<<<");
String msg = ds.getValue(String.class); // problem is here............................................
String time = ds.child("DateTime").getValue(String.class);
String tag = ds.child("Tag").getValue(String.class);
msg_List_Item msg_list_item = new msg_List_Item(msg, time, tag);
/* msg_list_item.setMsg(msg);
msg_list_item.setDateTime(time);
msg_list_item.setTag(tag);*/
msgList.add(msg_list_item);
MessageAdapter = new msgAdapter(msgList, getApplicationContext());
mRecyclerView.setAdapter(MessageAdapter);
sampleList.clear();
mRecyclerView.scrollToPosition(MessageAdapter.getItemCount());
}
}
}
else {
Toast.makeText(Message.this, "No data found", Toast.LENGTH_SHORT).show();
}}
#Override
public void onCancelled(DatabaseError databaseError) {
}}
);
"1234567890" : {
"-L7AhB1GWZPNqlte0tiX" : {
"DateTime" : "09-03-2018 22:30",
"MSG" : "hiii ",
"Tag" : "ByMe"
},
"-L7AiOxVbSYAx8_0WqEa" : {
"DateTime" : "09-03-2018 22:35",
"MSG" : "how are you",
"Tag" : "ByMe"
},
"-L7Ak1lhqn9EfD5YCOou" : {
"DateTime" : "09-03-2018 22:42",
"MSG" : "what are u doing?",
"Tag" : "ByMe"
},
"-L7AkGekOzKzlLOwWNWp" : {
"DateTime" : "09-03-2018 22:43",
"MSG" : "I am fine",
"Tag" : "NotByMe"
here is my Re modified structure!!!. *Child node : * "DateTime", "MSG", "Tag" become easier to fetch by using push().
{
"City" : {
"New York" : {
"City Name" : "New York",
"Place to visit" : {
"Times Square" : {
"Address" : "Somewhere",
"Name" : "Times Square"
},
"Central Park" : {
"Address" : "On America",
"Name" : "Central Park"
}
}
},
"Los Angeles" : {
"City Name" : "Los Angeles",
"Place to visit" : {
"Hollywood" : {
"Address" : "Up There",
"Name" : "Hollywood"
},
"Beach" : {
"Address" : "By the sea",
"Name" : "Beach"
}
}
}
}
}
Hi, I'm a little bit new to NoSQL database especially Firebase. If I structured my data like this, how can I get the name of "place to visit" where "City name" is New York?
And I want the result (Times Square and Central Park) to be shown as ListView. How can I achieve that?
Or is there any better way to restructure my data so I can query my desired output easier?
First of all city should hold a list of items (in your case city name "New York or Los Angeles").
By this it will be easier for you to traverse through the list and fetch desired city as required in a fastest and efficient manner, this is because you will get inbuilt methods to traverse.
I have also restructured your json response in order to make it a list of objects and removed redundant variables
Below is the response
{
"City": [{
"New York": {
"Place to visit": {
"Times Square": {
"Address": "Somewhere",
"Name": "Times Square"
},
"Central Park": {
"Address": "On America",
"Name": "Central Park"
}
}
}
},
{
"Los Angeles": {
"Place to visit": {
"Hollywood": {
"Address": "Up There",
"Name": "Hollywood"
},
"Beach": {
"Address": "By the sea",
"Name": "Beach"
}
}
}
}
]
}
Because the name of the city which you want to use in your query is already a node in your Firebase database, to get those names, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference placeToVisitRef = rootRef.child("City").child("New York").child("Place to visit");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String placeToVisit = ds.getKey();
Log.d("TAG", placeToVisit);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
placeToVisitRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
Times Square
Central Park
Try this one,
DatabaseReference ref= FirebaseDatabase.getInstance().getReference();
DatabaseReference refPlace= rootRef.child("City").child("New York").child("Place to visit");
refPlace.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshotsChat = dataSnapshot.child("articleTags").getChildren().iterator();
while (dataSnapshotsChat.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshotsChat.next();
// check dataSnapshotChild, here you will get the details under Place to visit
Object name = ds.child("Times Square").getValue(Object.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am trying to create chat app with Firebase database. I'm reading docs and watching tutorials but there is one thing I could not figure out how to do. When user sends message to another user, creating a chat room with key: "senderUserId_receiverUserId" You can see my structure below.
{
"chat_rooms" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2_oTLYaHMOMibh3ZqOcmpcWDtSCKp1" : {
"-KtQEGK38lhZrgnNxmqb" : {
"date" : "07/09/2017 10:28",
"message" : “Thanks for helping !”,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"receiverName" : "Ali”,
"receiverUid" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1",
"senderName" : “John”,
"senderUid" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2"
},
"-KtQEKK2BmIMzwruN-21" : {
"date" : "07/09/2017 10:28",
"message" : “Another Test Message“,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"receiverName" : “John”,
"receiverUid" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2",
"senderName" : "Ali",
"senderUid" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1"
},
"-KtQIGDk5zE4JZuE9pIQ" : {
"date" : "07/09/2017 10:45",
"message" : “Test message !“,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"receiverName" : “John”,
"receiverUid" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2",
"senderName" : "Ali",
"senderUid" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1"
}
}
},
"users" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2" : {
"address" : “istanbul”,
"cell_phone" : “none”,
"email" : “john#gmail.com",
"home_phone" : “none”,
"name" : “John”,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"userId" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2"
},
"oTLYaHMOMibh3ZqOcmpcWDtSCKp1" : {
"address" : “istanbul”,
"cell_phone" : “none”,
"email" : "ali#gmail.com”,
"home_phone" : “none”,
"name" : "Ali",
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"userId" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1"
}
}
}
With this way everything works fine but I don't know how to list user's all conversations at list like WhatsApp's Chats page. I mean when user clicks the conversations item, related conversation will be open.
I'm sending private messages with code below:
public void sendMessageToFirebaseUser(final Context context, final ChatMessageModel chat, final String receiverFirebaseToken) {
final String room_type_1 = chat.getSenderUid() + "_" + chat.getReceiverUid();
final String room_type_2 = chat.getReceiverUid() + "_" + chat.getSenderUid();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.getRef()
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(room_type_1)) {
Log.e("aaa", "sendMessageToFirebaseUser: " + room_type_1 + " exists");
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.child(room_type_1)
.push()
.setValue(chat);
} else if (dataSnapshot.hasChild(room_type_2)) {
Log.e("aaa", "sendMessageToFirebaseUser: " + room_type_2 + " exists");
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.child(room_type_2)
.push()
.setValue(chat);
} else {
Log.e("aaa", "sendMessageToFirebaseUser: success");
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.child(room_type_1)
.push()
.setValue(chat);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Thank you for reading my post.
If you want to show a list of chat rooms for the current user, you should model your data to allow that. The easiest way to do this is to add a list of chat rooms for each user to your data model:
"userChatrooms" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2_oTLYaHMOMibh3ZqOcmpcWDtSCKp1": true
},
"oTLYaHMOMibh3ZqOcmpcWDtSCKp1" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2_oTLYaHMOMibh3ZqOcmpcWDtSCKp1": true
}
}