Android : How to write Firebase realtime database query? - android

{
"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) {
}
});

Related

Get reference for my Firebase Query

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

Get a specific child from Firebase

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

How can i read this firebase database child nodes passing through the User Id?

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

Why does my child with space does not work in firebase?

My database is this ->
{
"140107": {
"Guest First Name": "As",
"Guest Last Name": "Rodrigues",
"Email": "aaa#yahoo.com.br",
"Country": "Brazil",
"Check-In date": "11-Jun-2016",
"Check-Out date": "12-Jun-2016",
"Room": "Cama Casal com suite",
"Unit No": 1,
"Subtotal": 90,
"Revenue": 90,
"Currency": "BRL",
"Create Date": "19-May-2016"
}
}
My code is this
public void ProcuraReservaporemail(){
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
myRef = database.getReference("reserva/");
myRef.orderByChild("Email").equalTo(email).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Reserva reserva1;
for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
// reserva1 = new Reserva(childSnapshot);
String Unit = (String) childSnapshot.child("Unit No").getValue();
textview2.setText(Unit);
textview2.setText( childSnapshot.child("Unit No").getValue(String.class));
}
}
The instruction childSnapshot.child("Unit No").getValue(String.class) generates an error because my bank with this space.I would have to change that so that this error does not happen anymore? I thought about changing all my bank more and more work.Do not have a specific error for the Activity stopped working.
Try using:
(String) childSnapshot.child("Unit No").getValue()
or
String.valueOf(childSnapshot.child("Unit No").getValue())

Firebase orderByChild and equalTo() queries don't work

I'm developing an Android app with the following Firebase database table:
"posts": {
"id_1": {
"author": "google:111527135678918251124",
"color": -2960686,
"creationTime": 1427104145195,
"text": "my text",
"title": "my Title",
"type": 0,
"visible": true
},
"id_2": {
"author": "google:111527135678918251524",
"color": -2960686,
"creationTime": 1427104145195,
"text": "my text",
"title": "my Title",
"type": 2,
"visible": true
},
"id_3": {
"author": "google:111527135678918251124",
"color": -2960686,
"creationTime": 1427104145195,
"text": "my text",
"title": "my Title",
"type": 1,
"visible": true
}
}
I'd like to be able to retrieve a the posts sorted by a child (sorted by type as an example) and be able to retrieve all the posts with a specific child value (type = 1).
Reading the Firebase docs it seems I have to write the following code, but I don't get the wanted result.
Order by type
rootRef.child("posts").orderByChild("type")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
result = (HashMap<String, Post>) dataSnapshot.getValue();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
I get: an unordered Map of Posts
Type = value
rootRef.child("posts").orderByChild("type").equalTo(1, "type").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
result = dataSnapshot.getValue();
result = result;
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
})
I get: null.
My Datasnapshot object has key = "posts" and value = null
About the ordering, I think the problem is that I'm retrieving data as a HashMap which is itself unordered.
As suggested in the comments the second case needs .equalTo(1) instead of .equalTo("type",1) because it's preceded by the .orderBy() method.

Categories

Resources