I uploaded such json to firebase console of realtime database. And to get some "words" im trying get child "words" with orderByChild ... startAt and so on...
Someone on this forum told me there is no any child in "words". Whats wrong?
{
"words" : {
"1" : {
"id" : 1,
"lang1" : "s1",
"lang2" : "d1",
"type" : "a"
} ,
"2" : {
"id" : 2,
"lang1" : "s2",
"lang2" : "d2",
"type" : "a"
} // ...
}
}
And my Java code:
Query fb = FirebaseDatabase
.getInstance()
.getReference()
.child("words")
.orderByChild("lang1")
.startAt("s2")
.limitToFirst(20);
BTW. I can not get any responce. This listener does not return anything.
fb.add... ValueEventListener() {
... void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Word w = singleSnapshot.getValue(Word.class);
Log.i(TAG, new Gson().toJson(w));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
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 want to retrieve only that post where postCategory matches the user interest.
How can I achieve this type of query. Any Help??
Below is my json file of database..
"Posts" : {
"-MAKobGjdhMfJFwZ1kol" : {
"postCategory" : "Animals",
"postDesc" : "still",
"postImage" : "Image Link",
"postPersonName" : "Name",
"postPersonUid" : "CLQA22uZpLS1ErIrnoBTrC3xqBw2",
"postTitle" : "ek"
},
"Users" : {
"CLQA22uZpLS1ErIrnoBTrC3xqBw2" : {
"email" : "email",
"interest" : {
"-MA14zFcNfs1JAjux129" : {
"name" : "Developer"
},
"-MA14zFgzhL-MOBB7D6h" : {
"name" : "Shopping"
}
},
"name" : "Name",
"uid" : "CLQA22uZpLS1ErIrnoBTrC3xqBw2"
}
In firebase database you cannot have such queries.
You should use Firestore (https://firebase.google.com/docs/firestore) for such advanced queries.
firestore/query-data
firestore
To get all posts with postCategory equal to Animals, you'd do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
Query query = ref.orderBy("postCategory").equalTo("Animals");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, postSnapshot.getKey()+": "+postSnapshot.child("postTitle").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
If you want to retrieve posts for multiple categories, you'll have to perform a separate query for each of those and merge the results on your client.
I'd also recommend changing how you store the categories for a user. The idiomatic way is:
"Users" : {
"CLQA22uZpLS1ErIrnoBTrC3xqBw2" : {
"email" : "email",
"interest" : {
"Developer": true,
"Shopping": true
}
},
The reasons this is more common is that it automatically ensures that each value can occur only once in the interest object, since property names are by definition unique.
I would like to know how can I retrieve the key of this object based on the object content. I'm using a realtime firebase database.
JSON code :
"Places" : {
"-M11-OIIHbKTVqCJ-Swv" : {
"name" : "Farmacia Pagani Dr. Roberto",
"others" : {
"Abilify" : 100,
"Acetaminophen" : 120,
"Acyclovir" : 140,
"Adderall" : 160
}
},
"-M11-OJJCGAPdJUknLXX" : {
"name" : "FARMACIA DR. TUMIATTI MARIANO",
"others" : {
"Abilify" : 100,
"Acetaminophen" : 120,
"Acyclovir" : 140,
"Adderall" : 160
}
}
I want to retrieve M11-OIIHbKTVqCJ-Swv if I have the name : Farmacia Pagani Dr. Roberto"
The code I wrote :
mUserDatabase = FirebaseDatabase.getInstance().getReference("Places");
Query query = mUserDatabase.orderByChild("name").equalTo(nameOfThePharmacy);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("The key is : "+dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
This code doesn't work, it returns : "Places" but I want the key of the object that contains the field name that equals with = ad example Farmacia Pagani Dr. Roberto , the output should be : -M11-OIIHbKTVqCJ-Swv
I have the following database structure -
{
"linking" : {
"shift-assign" : { // for every shift its assigned users
"key1" : {
"111" : true,
"222" : true
},
"key2" : {
"111" : true
}
},
"user-assign" : { // for every user its assigned shifts
"111" : {
"key1" : true,
"key2" : true
},
"222" : {
"key1" : true
}
}
},
"shifts" : {
"20191117" : {
"key1" : {
"endTime" : "00:00",
"numOfEmps" : 3,
"startTime" : "00:00",
"wage" : 0
},
"key2" : {
"endTime" : "00:00",
"numOfEmps" : 1,
"startTime" : "00:00",
"wage" : 0
}
}
},
"users" : {
"111" : {
"id" : "111",
"password" : "111"
},
"222" : {
"id" : "222",
"password" : "222"
},
"99999" : {
"id" : "99999",
"password" : "123",
}
}
}
Where a user can be assigned to several shifts and a shift can contain several users.
I'm currently trying to fetch all of the users assigned to a certain shift.
So the idea was attaching a ValueEventListener to linking/shift-assign/{shift-key}, run a loop and for every user-key , reference users/{user-key} and attach an inner ValueEventListener to read user object and add it to a userList.
Something like this :
mDatabase.child("linking/shift-assign").child(shiftKey)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot ds : dataSnapshot.getChildren()){
mDatabase.child("users").child(ds.getKey())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot2) {
mUser user = dataSnapshot2.getValue(mUser.class);
userList.add(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
adapter = new UsersAssignedAdapter(UsersAssignedActivity.this, userList);
lv.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
I debugged it and noticed that the for loop is finished before the inner ValueEventListener is called, which is why I'm getting an empty list in my adapter. I'm guessing this is due to its asynchronous behavior.
So my question is - is there any way I can query all user ids and for each one perform another query?
The example is parking spaces listing in a country.
The reason to structure the database with a userParkingDistanceMap is sorting by distance between the current user and all parking spaces.
The database query is .orderByChild("userParkingDistanceMap/" + getUid()).
So, how could I index this userParkingDistanceMapin Database Rules?
"parkingSpacesTokyo" : {
"parkingId5" : {
"parkingName" : "MY-PARKING-NAME",
"parkingQuantity" : 70,
"userParkingDistanceMap" : {
"uid-uid-uid-uid-uid-uid-uid" : 7983,
"9EAiImOh4ZUnqJ7em51u81FukD73" : 9456,
"AG84p8KJgANuobRJ5pn1ipxULFB3" : 8336,
"yYLVffMFsBQhsGHNWuPOksMDgip2" : 7983,
"yp6mZm2SPVhz5pOq57tSEZ40piJ2" : 7983
}
},
"parkingId6": {
...
}
},
"parkingSpacesYOKOHAMA" : {
}
So basically you might have initialized the reference by something like
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("parking");
ref.addListenerForSingleValueEvent(valueEventListner);
where valueEventListner is:
ValueEventListner valueEventListner = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for(DataSnapshot childDataSnapshot: dataSnapshot)
{
DatabaseReference parkindId = ref.child(dataSnapshot.getKey);
for(DataSnapshot parkingIdSnapshot : childDataSnapshot)
{
if(parkindIdSnapshot.hasChildren())
{
for(DataSnapshot distanceMap : parkingIdSnapshot)
{
String value = distanceMap.getValue(String.class);
}
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{}
});
Well I just wrote this code in direct answer so it's kind of psudo code so basically you might have got the idea about it. Best of luck.