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));
}
Related
I am using firebase realtime database in my first android app. I'm trying to retrieve data from firebase as an arraylist of "username" but i'm constantly having the Query returning a null result. i'm very new to firebase so i'm really struggling with data retrieval errors.
"Marchand" : {
"Taha" : {
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"
},
"Yasmine" : {
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"
}
.
.
.
This is one of my attempts, i tried to use the order-by-child method to iterate through the multiple nods that i have but i'm sure that it's not the right way to do this, this gives me null poiter exceptions because the datasnapshot is returning a NULL value :
referenceMarchand = rootNode.getReference("Marchand");
final ArrayList<String> types = new ArrayList<>();
Query users = referenceMarchand.orderByChild("username");
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
types.add(dataSnapshot.child("username").toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
lets make use of some functions of firebase, Lets see it works for you.
part 1)
we will save it another way around
"Merchant" : {"Name" : "Taha"
"ID" :"-KSMCMCMnnkd"},//Firebase generated id
{"Name" : "Yasmine"
"ID" :"-KSMCMccccnkd"},//Firebase generated Id
...........
Part 2)
And Save the Details
"Details" : {
"ID" : "-KSMCMCMnnkd" //Firebase generated id
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"},
{
"ID":"-KSMCMccccnkd" //Firebase generated id
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"}
In Part 1)
DatabaseRefrence ref = FirebaseDatabase.getInstance("/Path");
String id = ref.child("Merchant").push().getKey(); //Firebase generated id
Merchant merchant = new Merchant();
merchant.setId(id);
merchant.setName("SomeName");
ref.child("Merchant").child(id).setValue(merchant);
Part 2)
Detail detail = new Detail();
detail.setAddress("Some Address");
detail.setBlockage("false");
detail.setLatitude("SomeValue");
detail.setEmail("someText#gmail.com");
......
ref.child("Details").child(id).setValue(detail);
Now
List<Merchant> merchants = new ArrayList<>();
List<Detail> details = new ArrayList<>();
ref.child("Merchant").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Merchant merchant = snapshot.getValue(Merchant.class);
merchants.add(merchant);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ref.child("Details").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Detail detail = snapshot.getValue(Detail.class);
details.add(detail);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Now you can get the details for some merchant or save it in local database for later querying.
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
}
}
I'm working using Firebase this my database is looking like
my database screenshot
{
"CookerInfo" : {
"org1mLyyJNXtiGo8NimxhWvpId42" : {
"about" : "Cooker since 2005",
"address" : "agamy - italy ",
"available" : "tuesday from 5 am to 9 pm",
"cookerDishes" : {
"-Kk3RgXiUEgpgjF1aAdc" : {
"foodName" : "mol5ia",
"foodUrl" : "https://firebasestorage.googleapis.com/v0/b/fir-auth- aa979.appspot.com/o/dishphoto%2F1494723249227.jpg?alt=media&token=0fc03b18-d310- 493a-b332-c1f3e4896567",
"price" : "8 $",
"timeToPrepared" : "10 min",
"weight" : "100 gm "
}
},
"name" : "chef.mohamed",
"phone" : "0192822228",
"url" : "https://firebasestorage.googleapis.com/v0/b/fir-auth-aa979.appspot.com/o/cookerPhoto%2F1494723157098.jpg?alt=media&token=19e4e376-0013-4410-bc04-0483aff09902"
},
"vuUscH2L7wgtj2N3rGWOOjgv23s2" : {
"about" : "cookgood",
"address" : "alexandria",
"available" : "sunday",
"cookerDishes" : {
"-Kk32fy0FO1vtZgm6AOK" : {
"foodName" : "chiken",
"foodUrl" : "https://firebasestorage.googleapis.com/v0/b/fir-auth- aa979.appspot.com/o/dishphoto%2F1494716692079.jpg?alt=media&token=a70ed96e-acbc-45c6-95b7-4811fd8e2e26",
"price" : "10$",
"timeToPrepared" : "10 min",
"weight" : "100gm"
},
"-Kk32mfQWiMRLFV2SMo7" : {
"foodName" : "rise",
"foodUrl" : "https://firebasestorage.googleapis.com/v0/b/fir-auth- aa979.appspot.com/o/dishphoto%2F1494716718899.jpg?alt=media&token=6b9007f5-c22e-4ed4-83aa-a80f45e5363f",
"price" : "8 $",
"timeToPrepared" : "8 min",
"weight" : "50 gm"
}
},
"name" : "sherbini",
"phone" : "01093812681",
"url" : "https://firebasestorage.googleapis.com/v0/b/fir-auth-aa979.appspot.com/o/cookerPhoto%2F1494716634787.jpg?alt=media&token=2ba72b6d-0af0-4235-bff5-4b706e91486f"
}
}
}
And I want to reach to cookerDishes for specific cooker only (1 cooker) to put his dishes in gridview, however I don't save the ID in model.
I tried something like that, but it didn't work.
Query queryRef=mDatabaseRef.orderByChild("name")
.equalTo(COOKERNAME);
DatabaseReference node =queryRef.getRef();
node.child("cookerDishes").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children=dataSnapshot.getChildren();
for (DataSnapshot child : children){
FoodDish fooddish = new FoodDish();
String food_name =child.child("foodName").getValue(String.class);
fooddish.setFoodName(food_name);
foodList.add(fooddish);
}
gv.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I think you forgot to call notifyDataSetChanged() on your addapter
You don't need to call getRef() on the query. Instead you should attach the listener directly to the query:
Query queryRef=mDatabaseRef
.orderByChild("name")
.equalTo(COOKERNAME);
queryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot cookerSnapshot : dataSnapshot.getChildren()){
DataSnapshot cookerDishes = cookerSnapshot.getChild("cookerDishes"));
for (DataSnapshot dishSnapshot: cookerDishes.getChildren()) {
FoodDish fooddish = new FoodDish();
String food_name =child.child("foodName").getValue(String.class);
fooddish.setFoodName(food_name);
foodList.add(fooddish);
}
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());
}
});
This is my firebase database and further more is there. I just want to fetch all latitude and longitude of the users, but i cant pass through the UID
"user"
"ODs4wO19sLcht8bobUKFRVkIzu73" : {
"Email" : "jik#gmail.com",
"First Name" : "Dummy",
"Last Name" : "Name",
"Latitude" : "22.31179464",
"Longitude" : "73.18581206",
"Owner Address" : "bskksos",
"Profile Image" : "https://firebasestorage.googleapis.com/v0/b/streetfood2-4bd8a.appspot.com/o/Profile+Images%2Fcropped-1678023661.jpg?alt=media&token=43a13ac5-3dec-46b4-a38c-3c14475d42fa"
},
"OQu7N7hqJ6SLipqFwqutRozDtrz1" : {
"Email" : "fhfhd#gnail.com",
"First Name" : "shiv",
"Last Name" : "singh",
"Latitude" : "22.31179464",
"Longitude" : "73.18581206",
"Mobile Number" : "00000000",
"Password" : "qwerty",
"Profile Image" : "https://firebasestorage.googleapis.com/v0/b/streetfood2-4bd8a.appspot.com/o/Profile+Images%2Fcropped1324744850.jpg?alt=media&token=20a0efad-fb57-409d-a0d8-d6249366830d"
},
If you're looking to loop over all users:
DatabaseReference users = FirebaseDatabase.getInstance().getReference().child("Users");
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
double lat = userSnapshot.child("latitude").getValue(Double.class);
double lon = userSnapshot.child("longitude").getValue(Double.class);
System.out.println(lat+","+lon);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});